12

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?

Asons
  • 84,923
  • 12
  • 110
  • 165
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129

1 Answers1

28

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>
Asons
  • 84,923
  • 12
  • 110
  • 165
  • The link appears to work, but I don't see what relevance it has to this article, nor does it have the same title as the link suggests? – Oliver Joseph Ash Jun 26 '18 at 16:34
  • @OliverJosephAsh Ahh, now I see, it changes the URL completely when clicked on. Thanks, I will flag that for moderation and see what they say. – Asons Jun 26 '18 at 16:36
  • @OliverJosephAsh Someone changed the title of that older question. I now updated the link to one of its answer, which talks about a block elements background color, which have the similar effect on overflowed child block elements, hence its description is of value for this answer of mine as well. – Asons Jun 26 '18 at 16:46
  • Also worth noting that if you also want the container to never shrink below its parent size (i.e. when its children are smaller), you need to use `min-width: 100%`. Alternatively, you can replace both the inline display and the `min-width` with the new `min-width: min-content`. http://jsbin.com/xumeqik/2/edit?html,css,output – Oliver Joseph Ash Jun 27 '18 at 11:15