By removing the width:100%
, a clearer understanding can be obtained:
section {
background: lightgrey;
width: 1000px;
}
div {
background: red;
display: flex;
}
form {
background: blue;
box-sizing: border-box;
}
input {
box-sizing: border-box;
margin: 0.3125em 0 0.625em;
}
<section>
One input field.
<div>
<form action="">
<input type="text">
</form>
</div>
</section>
<section>
Two input fields.
<div>
<form action="">
<input type="text">
<input type="text">
</form>
</div>
</section>
<section>
Three input fields.
<div>
<form action="">
<input type="text">
<input type="text">
<input type="text">
</form>
</div>
</section>
<section>
Four input fields.
<div>
<form action="">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</form>
</div>
</section>
The blue box's width is determined by the inputs, and this width serves as the reference for width: 100%;
, causing all inputs to expand to full width.
In essence, percentage values require a reference point, so the blue box's width is calculated based on its content before being used as a reference for the inputs.
This scenario also applies to simple inline-block elements
section {
background: lightgrey;
width: 1000px;
}
div {
background: red;
display: inline-block;
}
form {
background: blue;
box-sizing: border-box;
}
input {
box-sizing: border-box;
width:100%;
margin: 0.3125em 0 0.625em;
}
<section>
<div>
<form action="">
<input type="text">
</form>
</div>
</section>
<section>
<div>
<form action="">
<input type="text">
<input type="text">
</form>
</div>
</section>
<section>
<div>
<form action="">
<input type="text">
<input type="text">
<input type="text">
</form>
</div>
</section>
<section>
<div>
<form action="">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</form>
</div>
</section>
For more information on percentage sizing, visit: https://www.w3.org/TR/css-sizing-3/#percentage-sizing
An explicit example illustrating this behavior can be found here:
For instance, in the following markup:
<article style="width: min-content">
<aside style="width: 50%;">
LOOOOOOOOOOOOOOOOOOOONG
</aside>
</article>
When calculating the width of the outer <article>
, the inner <aside>
behaves as width: auto
. Thus, the <article>
adapts itself to the width of the lengthy word. Even though the <article>
's width isn't impacted by the "real" layout, it is treated as definitive for resolving the <aside>
, whose width ends up being half of the <article>
.
When utilizing display: block, everything functions as intended.
The calculation of block element widths operates differently than that of content-dependent inline-block elements or flex items, where the content dictates the width