display: inline-block extra margin [duplicate]

2018-12-31 16:13发布

This question already has an answer here:

I'm working with a few divs that are set to display: inline-block and have a set height and width. In the HTML, if there is a line break after each div there is an automatic 5px margin add to the right and bottom of the div.

Example:

<div>Some Text</div>
<div>Some Text</div>

Is there a property that I've overlooked that will allow me to reset the automatic margin?

Update

From what I've found there is no way to remove the margin... except if you either have everything on the same line or, add comments to comment out the line breaks. example:

<div>Some Text</div><!--
--><div>Some Text</div>

Not the best solution, but still easier to read if you have multiple lines.

标签: html css xhtml
12条回答
唯独是你
2楼-- · 2018-12-31 16:47

A year later, stumbled across this question for a inline LI problem, but have found a great solution that may apply here.

http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

vertical-align:bottom on all my LI elements fixed my "extra margin" problem in all browsers.

查看更多
查无此人
3楼-- · 2018-12-31 16:47

There are a number of workarounds for this issue which involve word-spacing or font size but this article suggests removing the margin with a right margin of -4px;

http://designshack.net/articles/css/whats-the-deal-with-display-inline-block/

查看更多
像晚风撩人
4楼-- · 2018-12-31 16:48

You can get a vertical space even though you have NO WHITESPACE whatsoever between your inline-block elements.

For me, this was caused by line-height. The simple fix was:

div.container {
    line-height: 0;
}
div.container > * {
    line-height: normal;
}
查看更多
浪荡孟婆
5楼-- · 2018-12-31 16:49

font-size: 0 to parent container

(Source: https://twitter.com/garand/status/183253526313566208)

查看更多
梦该遗忘
6楼-- · 2018-12-31 16:49

Another solution to this is to use an HTML minifier. This works best with a Grunt build process, where the HTML can be minified on the fly.

The extra linebreaks and whitespace are removed, which solves the margin problem neatly, and lets you write markup however you like in the IDE (no </li><li>).

查看更多
流年柔荑漫光年
7楼-- · 2018-12-31 16:51

The divs are treated as inline-elements. Just as a space or line-break between two spans would create a gap, it does between inline-blocks. You could either give them a negative margin or set word-spacing: -1; on the surrounding container.

查看更多
登录 后发表回答