geoyws geoyws - 6 months ago 16
HTML Question

Padding-left of inline container does not pad. Why?

Can anyone point me to specs?



x-x {
padding: 10px;
}

<x-x>
<div>1</div>
<div>2</div>
</x-x>






  • padding-left does not pad

  • however, padding-top and padding-bottom does

  • why is this?



http://codepen.io/geoyws/pen/NNJjPV

Answer

Your custom element (<x-x>) defaults to CSS initial values. So its display value is inline.

This element contains two divs, which are block-level elements.

Because an inline box cannot wrap a block-level box, the browser implicitly closes the <x-x> before it wraps the div.

Hence, the reason the left padding is not working is because the custom element is not actually wrapping the two divs. It's closed right before the first opening <div>.

However, if you put a span in the custom element, the padding will work, because a span is display: inline by default (demo).

All this can be verified in dev tools. Highlight the custom element to see that it doesn't wrap the divs.

Here's more from the specs:

First, using an inline-level element to wrap block-level elements is invalid HTML.

7.5.3 Block-level and inline elements

Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.

(emphasis added)

Second, inline-level elements to "break around" block-level boxes.

9.2.1.1. Anonymous block boxes

When an inline box contains an in-flow block-level box, the inline box (and its inline ancestors within the same line box) are broken around the block-level box (and any block-level siblings that are consecutive or separated only by collapsible whitespace and/or out-of-flow elements), splitting the inline box into two boxes (even if either side is empty), one on each side of the block-level box(es). The line boxes before the break and after the break are enclosed in anonymous block boxes, and the block-level box becomes a sibling of those anonymous boxes. When such an inline box is affected by relative positioning, any resulting translation also affects the block-level box contained in the inline box.