Shrink flexbox container width to row content width in multi-row box

Viewed 19

I have the following code (Fiddle https://jsfiddle.net/49dvm6h1/39/)

<!DOCTYPE html>
<html>
<body>
  <div class="outer">
    <div class="inner">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
    </div>
  </div>
  
  <style>
  
    .outer {
      max-width: 500px;
      background: red;
    }
  
    .inner {
      padding: 4px;
      background: green;
      display: inline-flex;
      align-items: center;
      flex-flow: row wrap;
      gap: 4px;
    }
    
    .item {
      width: 200px;
      height: 50px;
      background: #0000ff;
    }
  </style>
</body>
</html>

Is it event possible to make the green container reduce it's width to it's content without JS or Media Quieres & breakpoints?

1 Answers

You have 2 Blue boxes in a row, which is 200px width each (200px * 2 = 400px).

  • You have left, center and right Gap of 4px each (4px * 3 = 12px)
  • So add those Values = 400px + 12px = 412px

Set that max-width on your outer class and not 500px.

So it will fix your problem.

<!DOCTYPE html>
<html>
<body>
  <div class="outer">
    <div class="inner">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
    </div>
  </div>
  
  <style>
  
    .outer {
      max-width: 412px;
      background: red;
    }
  
    .inner {
      padding: 4px;
      background: green;
      display: inline-flex;
      align-items: center;
      flex-flow: row wrap;
      gap: 4px;
    }
    
    .item {
      width: 200px;
      height: 50px;
      background: #0000ff;
    }
  </style>
</body>
</html>

Related