When do margins render on empty inline elements?

2020-05-27 06:02发布

When do margins render on empty inline elements, according to the specs, and in browsers? The following code has been tested in chrome (webkit).

This code displays no margin:

<p>Example <span style="margin:2em"> </span>Example</p>

And this code does:

<p>Example <span style="margin:2em"></span>Example</p>

I understand that in the first example, the white space is collapsed, but that should make it equivalent to the second example? So why & when?

Fiddle

标签: html css
1条回答
够拽才男人
2楼-- · 2020-05-27 06:45

The spec says that whitespace should be collapsed even if an inline element begins after whitespace and starts with whitespace (i.e. the opening tag appears in the middle of whitespace as in your first span element):

any space (U+0020) following another space (U+0020) — even a space before the inline, if that space also has 'white-space' set to 'normal', 'nowrap' or 'pre-line' — is removed.

For your first span element, this should result in an empty element. An empty inline element should still generate an empty box, albeit with zero width since there is nothing inside, and margins should still take effect since the box is always rendered:

Empty inline elements generate empty inline boxes, but these boxes still have margins, padding, borders and a line height, and thus influence these calculations just like elements with content.

According to Chrome's Web Inspector, it looks like it's failing to generate the box for the span element entirely as it collapses the space in the element into the space that comes just before it. When the span element is empty in the source, it generates an empty box with margins correctly. All other browsers have no trouble drawing an empty box after they perform whitespace collapsing, and the spec doesn't say anything about deleting a non-anonymous box if it was made empty by the process of whitespace collapsing, so I would say that this is a Chrome bug.

As mentioned in the comments, this issue affects the latest versions of Chrome as well, which use Blink. Blink is a fork of WebKit after all, so it's not surprising to see that most of the CSS2.1 bugs plaguing WebKit haven't been fixed in Blink yet.

查看更多
登录 后发表回答