I\'m implementing a form which has multiple sections with different numbers of input fields. When using display: flex
on the parent div and 100% width on the input
Simply remove width:100%
and you will better understand:
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;
}
One input field.
Two input fields.
Three input fields.
Four input fields.
The inputs are defining the width of the blue box and then this width will be the reference of the width: 100%;
making all the input to be full width of it.
Basically, a percentage value need a reference so the width of the blue box is first calculated considering the content and then the input will use that width as reference.
This can also happen with 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;
}
More details about percentage sizing here: https://www.w3.org/TR/css-sizing-3/#percentage-sizing
You can find an explicit example of such behavior:
For example, in the following markup:
When calculating the width of the outer
, the inner
behaves as
width: auto
, so thesets itself to the width of the long word. Since the
’s width didn’t depend on "real" layout, though, it’s treated as definite for resolving the
, whose width resolves to half that of the
.
When using display: block, everything works as intended.
Simply because the width calculation of block element is different and doesn't depend on the content unlike for inline-block elements or flex items where the content define the width