Why doesn’t a parent element with a background cover a child element with a width larger than the viewport?
Take this simple HTML:
#parent element’s pink background doesn’t persist across the entire
#child element. Why is this?
Setting the background on the
body element does apply to the entire
#child, even though the
body share the same width, i.e. the viewport width.
Curiously, setting the
#parent element’s display to
inline-block fixes this issue, though I have no idea why!
Any help here would be greatly appreciated :)
#parent’s pink background doesn’t persist across the entire
#child. Why is this?
It’s because a block-level element has a default width of
100%. In this case, it has a width of
100% of the
body element, which is the same as the viewport.
In other words, even though the element’s child has a width of
5000px, it will still have a width of
100% of whatever the viewport is, which means that the background will not extend to cover the child element. The reason this doesn’t apply to the
body element is because the
body element is a special case, and the values are treated as if they were specified on the root element. See:
The used values of that
bodyelement’s background properties are their initial values, and the propagated values are treated as if they were specified on the root element.> Curiously, setting the
inline-blockfixes this issue, though I have no idea why!
That’s because it is no longer a block-level element with a width of
inline-block elements have a “shrink-to-fit” width, which means that they will take the width of the child element. Similarly adding
display: table would have similar results.