SaroVin SaroVin - 3 years ago 106
CSS Question

How to adapt div's width to content with flexbox

I want adapt the

.flexrow
div's width to content but i can't set it with flex.

HTML

<div class="fullwidth">
<div class="sidebar">
<p>sidebar</p>
<p>sidebar</p>
<p>sidebar</p>
<p>sidebar</p>
<p>sidebar</p>
<p>sidebar</p>
</div>
<div class="center">
<div class="flexrow">
<div class="card">
<p>card</p>
</div>
</div>
</div>
</div>


CSS

.center {
display: flex;
justify-content: center;
}

.flexrow {
display: inline-flex;
flex-direction: row;
flex-wrap: wrap;
}

.flexrow .card {
width: 300px;
height: 60px;
background-color: red;
margin: 10px;
padding: 10px;
text-align: center;
}


I have created a snippet here

This is an example of what i want:
example

Any suggestion?

Answer Source

The main problem here is that when an item wrap, whether one use Flexbox or not, its container won't adjust its width to the new content width.

With the existing markup, here is a simple fix in 2 steps to achieve that:

  1. Add justify-content: center; to your .flexrow rule

  2. For every possible column you need one less ghost element to push elements on the last row all the way to the left. The added elements together with new .flexrow .card:empty rule will do the magic.

    .flexrow .card:empty {
      height: 0;
      margin: 0 10px;
      padding: 0 10px;
    }
    

Updated codepen

Stack snippet

.fullwidth {
  background-color: grey;
  display: flex;
}

.sidebar {
  flex: 0 0 280px;
  margin: 10px;
  padding: 10px;
  background-color: black;
  color: white;
}

.flexrow {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: center;
}

.flexrow .card {
  width: 300px;
  height: 60px;
  background-color: red;
  margin: 10px;
  padding: 10px;
  text-align: center;
}

.flexrow .card:empty {
  height: 0;
  margin: 0 10px;
  padding: 0 10px;
}
<div class="fullwidth">
  <div class="sidebar">
    <p>sidebar</p>
    <p>sidebar</p>
    <p>sidebar</p>
    <p>sidebar</p>
    <p>sidebar</p>
    <p>sidebar</p>
  </div>
  <div class="center">
    <div class="flexrow">
      <div class="card">
        <p>card</p>
      </div>
      <div class="card">
        <p>card</p>
      </div>
      <div class="card">
        <p>card</p>
      </div>
      <div class="card">
        <p>card</p>
      </div>
      <div class="card">
        <p>card</p>
      </div>
      <div class="card">
        <p>card</p>
      </div>
      <div class="card">
        <p>card</p>
      </div>

      <!-- Ghost elements, if max columns is 4 one need 3 -->
      <div class="card"></div>
      <div class="card"></div>
      <div class="card"></div>

    </div>
  </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download