How to make CSS grid wrap its contents?

Spread the love

Sometimews, we want to make CSS grid wrap its contents.

In this article, we’ll look at how to make CSS grid wrap its contents.

How to make CSS grid wrap its contents?

To make CSS grid wrap its contents, we use the auto-fill style.

For instance, we write

<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

to add nested divs.

Then we write

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 186px);
}

.grid > * {
  background-color: green;
  height: 200px;
}

to make the outer div a grid container with display: grid;.

Then we use grid-template-columns: repeat(auto-fill, 186px); to set each child div to 186px wide and wrap anything that overflows the container.

Conclusion

To make CSS grid wrap its contents, we use the auto-fill style.

Leave a Reply

Your email address will not be published.