Your analysis is missing one crucial element - the overflow part. It is accurate to say that one
will inherit the width of its parent, but two
will not expand the width of its parent; instead, it will overflow it.
If you add a border to the body
and html
elements, this difference becomes more apparent.
div {
border: 1px solid red;
}
.two {
width: 1000px;
}
body {
border:2px solid;
}
html {
border:2px solid green;
}
<div class="one">Hello World</div>
<div class="two">Hello World</div>
Starting from the viewport, all elements are block-level and will have a default width of 100%
(html
, then body
, then one
). However, setting the width of two
larger creates an overflow without impacting any ancestor elements' widths.
To fully understand how overflow works and when scrollbars are added:
UAs must apply the 'overflow' property set on the root element to the viewport. When the root element is an HTML "HTML" or XHTML "html" element with an HTML "BODY" or XHTML "body" child element, user agents should apply the 'overflow' property from the first child element to the viewport if the value on the root element is 'visible'. The 'visible' value for the viewport should be interpreted as 'auto'. The element propagating the value must have a 'used value for 'overflow' of 'visible'. ref
In our case, we didn't specify an overflow value, so by default, it's visible
, resulting in a scrollbar on the viewport rather than the html
or body
.
Auto
The behavior of the 'auto' value varies between user agents but typically adds a scrolling mechanism for overflowing content boxes.
If you disable overflow within the html
or body
, no scrollbar will appear:
div {
border: 1px solid red;
}
.two {
width: 1000px;
}
body {
border:2px solid;
overflow:hidden;
}
html {
border:2px solid green;
}
<div class="one">Hello World</div>
<div class="two">Hello World</div>
And for the html
:
div {
border: 1px solid red;
}
.two {
width: 1000px;
}
body {
border:2px solid;
}
html {
border:2px solid green;
overflow:hidden;
}
<div class="one">Hello World</div>
<div class="two">Hello World</div>
Changing your body
display property to inline-block
will demonstrate that the width increases based on content and is no longer confined to width:100%
:
div {
border: 1px solid red;
}
.two {
width: 1000px;
}
body {
border:2px solid;
display:inline-block;
}
html {
border:2px solid green;
}
<div class="one">Hello World</div>
<div class="two">Hello World</div>