Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make flex container width grow as its children

Tags:

html

css

flexbox

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?

like image 554
Alexander Abakumov Avatar asked Oct 09 '17 16:10

Alexander Abakumov


People also ask

How do you increase flexbox width?

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.

How can you cause a flex item to grow in size?

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.

How do you change the width of a flex column?

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".


1 Answers

Block element grows to its parent width, inline grows with its content.

A great and more in-depth explanation can be found here:

  • Make background color extend into overflow area

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>
like image 128
Asons Avatar answered Oct 19 '22 01:10

Asons