By default, the items tend to fit into one line. With CSS grid-template-columns property, we can specify how many items to insert in a row.

Let’s take an example with the following HTML Structure:

<div class="grid-container">
  <div class="grid-item">Item 1</div>
  <div class="grid-item">Item 2</div>
  <div class="grid-item">Item 3</div>
  <div class="grid-item">Item 4</div>
  <div class="grid-item">Item 5</div>
  <div class="grid-item">Item 6</div>
</div>

To make 3 items per row, we write the CSS:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

In this example, we use the repeat() function to specify that there should be three columns with equal width, and each column should take up 1 fraction of the available space (i.e., 1fr).

You can adjust the number of items per row by changing the number in the repeat() function. For example, grid-template-columns: repeat(4, 1fr); would create a grid with four items per row.

You can also make “x” items per row using CSS Flexbox, and using CSS Table Layout.

For a comprehensive guide, check out CSS Grid – learning by doing!

CSS Grid: Making “x” items per row
Tagged on:

Sanjeev Aryal

Don't bury your thoughts, put your vision into reality ~ Bob Marley.

Leave a Reply

Your email address will not be published. Required fields are marked *