2

I have a flex box layout. I want the width of .outer-2 to be the width of its children, with .outer-1 and outer-3 taking up the rest of the space.

How can I achieve this?

JSFiddle

.container {
  display: flex;
}

.outer-1 {
  background: red;
  height: 100px;
  flex: 1;
}

.outer-2 {
  display: flex;
  flex: 1;
}

.outer-3 {
  background: blue;
  height: 100px;
  flex: 1;
}

.inner {
  flex-basis: 30px;
  background: green;
  height: 100px;
  margin: 0 3px;
}
<div class="container">
  <div class="outer-1">
  </div>
  <div class="outer-2">
    <div class="inner">
    </div>
    <div class="inner">
    </div>
    <div class="inner">
    </div>
  </div>
  <div class="outer-3">
  </div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
panthro
  • 22,779
  • 66
  • 183
  • 324
  • Is it what you wants? [Fiddle](https://jsfiddle.net/Muhammad_Usman/v8tgyvbd/1/) – Mohammad Usman Mar 17 '17 at 13:19
  • Muhammad Usman - almost, although in your example flex basis has no effect. – panthro Mar 17 '17 at 13:23
  • Is using CSS grids an option? This layout might be easier with that. – Brian Glaz Mar 17 '17 at 13:35
  • Two steps: (1) remove `flex: 1` from `.outer-2`. Telling the middle item to share equal width with its siblings is counter to your objective. (2) replace `flex-basis: 30px` with `width: 30px`. `flex-basis` isn't working as expected in this case. Not sure why. Maybe a bug. https://jsfiddle.net/v8tgyvbd/3/ – Michael Benjamin Apr 02 '17 at 14:38

1 Answers1

2

You need to change the flex properties for the second child of container preventing it from growing to fit it's parent. That, and adding a width or min-width to each .inner element will prevent their parent from collapsing them down.

.container{
  display: flex;
}
.outer-1{
  background: red;
  height: 100px;
  flex: 1;
}
.outer-2{
  display: flex;
  flex: 1;
}
.outer-3{
  background: blue;
  height: 100px;
  flex: 1;
}
.inner{
  width: 30px;
  flex: 1 0 30px;
  background: green;
  height: 100px;
  margin: 0 3px;
}
<div class="container">
  <div class="outer-1">
  
  </div>
  <div class="outer-2">
      <div class="inner">
  
      </div>
      <div class="inner">
  
      </div>
      <div class="inner">
  
      </div>
  </div>
  <div class="outer-3">
  
  </div>
</div>
chazsolo
  • 7,873
  • 1
  • 20
  • 44