This is simplified layout:
<div class="root">
<div class="container">
<div class="cell">
<input type="text" class="contact"></input>
</div>
</div>
</div>
And this is simplified CSS:
.root {
background-color: red;
overflow: auto;
width: 300px;
}
.container {
background-color: green;
display: flex;
height: 50px;
}
.cell {
background-color: black;
height: 30px;
}
.contact {
width: 400px;
}
This is jsFiddle.
It is somewhat unexpected to me that the container
width isn't the same as it is required by its child and rather is as limited by the root
div
. You can see in this jsFiddle that red area (root div
) isn't filled with the green container
div
.
Could someone explain why flex
container width doesn't grow as its children and how to fix that?
A flexbox item can be set to a fixed width by setting 3 CSS properties — flex-basis, flex-grow & flex-shrink. flex-basis : This property specifies the initial length of the flex item. flex-grow : This property specifies how much the flex item will grow relative to the rest of the flex items.
flex: 1 0 200px; If you have one element that has a flex-basis of 200px, flex-grow of 1, and flex-shrink of 0, this element will be at minimum 200px wide, but it will be allowed to grow if there is extra space. In this case, you can think of the flex-basis as being a minimum width.
If you want to have a fixed-width column with Flexbox, you need to use the CSS flex or flex-basis property. First of all, we set the display of our <div> container to "flex". Then, we specify the flex of the "grey" class as "0 0 50px".
Block element grows to its parent width, inline grows with its content.
A great and more in-depth explanation can be found here:
Change to inline-flex
and you get the expected result.
.root {
background-color: red;
overflow: auto;
width: 300px;
}
.container {
background-color: green;
display: inline-flex; /* changed */
height: 50px;
}
.cell {
background-color: black;
height: 30px;
}
.contact {
width: 400px;
}
<div class="root">
<div class="container">
<div class="cell">
<input type="text" class="contact">
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With