Alexander Abakumov
Alexander Abakumov

Reputation: 14539

Make flex container width grow as its children

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?

Upvotes: 12

Views: 17220

Answers (1)

Asons
Asons

Reputation: 87191

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>

Upvotes: 29

Related Questions