Set min-width either by content or 200px (whichever is greater) together with max-width

Anton Harald picture Anton Harald · Mar 26, 2015 · Viewed 134.8k times · Source

I need this:

Container width is fixed width, items flowing in the row direction and wrapping at the end.

each item should be max-width: 400px, overflowing content should be cut. The minimum width of the items should be determined by the content, however: it should never be shorter than 200px.

Here is my CSS code, it does not cover the "min-content" aspect. min-content is suggested by the w3 in their Flexbox working draft, but it does not seem to work in my case:

.container {
    display: -webkit-flex;
    display: flex;
    -webkit-flex-wrap: wrap;
    flex-wrap: wrap;
}

.container .box {
    -webkit-flex: 1;
    flex: 1;
    min-width: 200px;
    max-width: 400px;
    height: 200px;
    background-color: #fafa00;
    overflow: hidden;
}

and the HTML is:

<div class="container">
    <div class="box">
        <table>
            <tr>
                <td>Content</td>
                <td>Content</td>
                <td>Content</td>
            </tr>
        </table>    
    </div>
    <div class="box">
        <table>
            <tr>
                <td>Content</td>
            </tr>
        </table>    
    </div>
    <div class="box">
        <table>
            <tr>
                <td>Content</td>
                <td>Content</td>
            </tr>
        </table>    
    </div>
    [...]
</div>

Answer

Oriol picture Oriol · May 24, 2015

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

.container {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}

.container .box {
  -webkit-flex-grow: 1;
  flex-grow: 1;
  min-width: 100px;
  max-width: 400px;
  height: 200px;
  background-color: #fafa00;
  overflow: hidden;
}
<div class="container">
  <div class="box">
    <table>
      <tr>
        <td>Content</td>
        <td>Content</td>
        <td>Content</td>
      </tr>
    </table>    
  </div>
  <div class="box">
    <table>
      <tr>
        <td>Content</td>
      </tr>
    </table>    
  </div>
  <div class="box">
    <table>
      <tr>
        <td>Content</td>
        <td>Content</td>
      </tr>
    </table>    
  </div>
</div>