The following snippet is an example of text boxes that do not cause overflow when the viewport is resized to be smaller than the specified (maximum) width. This is achieved by requesting each <input> to take up 100% of the available width, but no more than a specific limit.
.block {
display: block;
}
.w-full {
width: 100%
}
.max-w-80 {
max-width: 20rem;
}
.max-w-20 {
max-width: 5rem;
}
<label for="ex1" class="block">First Name</label>
<input id="ex1" type="text" class="w-full max-w-80"/>
<label for="ex2" class="block">Last Name</label>
<input id="ex2" type="text" class="w-full max-w-20"/>
However, if these inputs are placed on the same line via flexbox, the longer <input> element reverts to the browser default width.
.block {
display: block;
}
.flex {
display: flex;
}
.w-full {
width: 100%
}
.max-w-80 {
max-width: 20rem;
}
.max-w-20 {
max-width: 5rem;
}
<div class="flex">
<div>
<label for="ex1" class="block">First Name</label>
<input id="ex1" type="text" class="w-full max-w-80"/>
</div>
<div>
<label for="ex2" class="block">Last Name</label>
<input id="ex2" type="text" class="w-full max-w-20"/>
</div>
</div>
This can be alleviated by making the wrapping <div>s grow to take up more space, but if the viewport is wide enough, there will be blank space between the inputs (i.e. the inputs will not be directly next to each other anymore).
.block {
display: block;
}
.flex {
display: flex;
}
.w-full {
width: 100%
}
.max-w-80 {
max-width: 20rem;
}
.max-w-20 {
max-width: 5rem;
}
.grow {
flex-grow: 1;
}
<div class="flex">
<div class="grow">
<label for="ex1" class="block">First Name</label>
<input id="ex1" type="text" class="w-full max-w-80"/>
</div>
<div class="grow">
<label for="ex2" class="block">Last Name</label>
<input id="ex2" type="text" class="w-full max-w-20"/>
</div>
</div>
A patch for this would be to apply the maximum width of the <input> to the wrapping <div> as well, but this would also force the <label> to be constrained to the same size. This is problematic if the label is longer than the text box.
.block {
display: block;
}
.flex {
display: flex;
}
.w-full {
width: 100%
}
.max-w-80 {
max-width: 20rem;
}
.max-w-20 {
max-width: 5rem;
}
.grow {
flex-grow: 1;
}
<div class="flex">
<div class="grow max-w-80">
<label for="ex1" class="block">First Name</label>
<input id="ex1" type="text" class="w-full max-w-80"/>
</div>
<div class="grow max-w-20">
<label for="ex2" class="block">Phone Number</label>
<input id="ex2" type="text" class="w-full max-w-20"/>
</div>
</div>
Is there a way to make the immediate children of a flexbox (the <divs> in this case) grow to take up as much width as possible, but no more than the maximum width of the longest element nested within in it?
I'm sure this is achievable with JavaScript, but I'm hoping that a CSS/HTML-only solution exists.