Search code examples
htmlcssflexbox

Taking up maximum space inside a box before wrapping?


So I need to display a box (position absolute) above my page when clicking on some button designed, inside this box will be a list of "tags" which should be displayed in a row. But my problem is that I cannot manage to make the tags wrap properly, taking the maximum space of the box. I want to display as many tags as possible in a single row.

Any idea if this is possible ?

https://jsfiddle.net/e18d2ajh/

.vectors {
  display: inline-flex;
  min-width: 20vw;
  max-width: 50vw;
  background-color: #333;
  padding: 15px;
  margin-bottom: 15px;
}
  
.vector {
  display: flex;
  padding: .35rem;
  background-color: #c0c0c0;
  margin-right: .5rem;
}
<h5>
  with few boxes
</h5>
<div class="vectors">
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
</div>

<h5>
  with many boxes
</h5>
<div class="vectors">
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
  <div class="vector">
    Random text
  </div>
</div>


Solution

  • Use flex-wrap property to wrap contents to next line

    .vectors {
      ...
      flex-wrap: wrap;
      ...
    }
    

    .vectors {
      display: inline-flex;
      flex-wrap: wrap;
      min-width: 20vw;
      max-width: 50vw;
      background-color: #333;
      padding: 15px;
      margin-bottom: 15px;
    }
      
    .vector {
      display: flex;
      padding: .35rem;
      background-color: #c0c0c0;
      margin-right: .5rem;
    }
    <h5>
      with few boxes
    </h5>
    <div class="vectors">
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
    </div>
    
    <h5>
      with many boxes
    </h5>
    <div class="vectors">
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
      <div class="vector">
        Random text
      </div>
    </div>