0

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

mr.boris
  • 3,667
  • 8
  • 37
  • 70
  • 2
    A grid is a series of tracks arranged in columns and rows. The columns are **one width** from top to bottom. In other words, a "fixed width." A column can't have different widths on different rows because then you don't have a grid (like in your first image). Flexbox may be a better solution in this case. – Michael Benjamin Aug 18 '23 at 00:09

1 Answers1

1

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>
Brett Donald
  • 6,745
  • 4
  • 23
  • 51
  • Thank you for this example! I forgot that flexbox supports `gap` property too (there was a time when there was no support). I hope that no one needs to use such wrapping behavior in conjunction with the grid otherwise someone will have to wrestle with the solution. – mr.boris Aug 18 '23 at 08:24
  • You can nest a flexbox inside a grid if you need to. – Brett Donald Aug 19 '23 at 01:29