cssflexboxcss-gridflexboxgrid

CSS Grid: wrap & fit to content


I want to wrap my list and at the same time make it fit to the content like this:

enter image description here

The problem is that each element must fit the width of its content.

I've already found example how to wrap items of fixed size but it doesn't help me in my case: grid-template-columns: repeat( 12, minmax(250px, 1fr) );

I tried several combinations but without success, the list is either fixed in one row, or the elements overlap each other. Also I can't find any good example for this case.

<style>
.container {
  width: 450px;
  padding: 5px;
  border: 1px solid black;
  display: grid;
  gap: 10px;
  grid-template-columns: repeat( auto-fit, minmax(min-content, 30px) );
}
.item {
  padding: 5px;
  border: 1px solid black;
  border-radius: 7px;
  white-space: nowrap;
}
</style>
<div class="container">
  <div class="item">First item</div>
  <div class="item">Second item</div>
  <div class="item">Some text here</div>
  <div class="item">Example</div>
  <div class="item">Wrapped item</div>
  <div class="item">Another wrapped item</div>
</div>

This is what I get for now:

enter image description here


Solution

  • A grid produces rows and columns, like a spreadsheet. The layout you're after is best achieved using a flexbox.

    .container {
      width: 450px;
      padding: 5px;
      border: 1px solid black;
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
    .item {
      padding: 5px;
      border: 1px solid black;
      border-radius: 7px;
      white-space: nowrap;
    }
    <div class="container">
      <div class="item">First item</div>
      <div class="item">Second item</div>
      <div class="item">Some text here</div>
      <div class="item">Example</div>
      <div class="item">Wrapped item</div>
      <div class="item">Another wrapped item</div>
    </div>