CSS Grid is a modern way of designing a responsive layout. It’s a powerful and flexible way to design web pages compared to traditional floats and positioning. Float is also a modern way but it focuses on one dimensional layout either row or column while grid is flexible for both rows and columns. If you’re working with Flex, you may want to look into making X items per row using CSS Flexbox.
For now, let’s focus on the CSS Grid.
Let’s assume the HTML for all the examples below:
<div class="grid-container">
<div class="item1">1</div>
<div class="item2">2</div>
<div class="item3">3</div>
<div class="item4">4</div>
<div class="item5">5</div>
<div class="item6">6</div>
<div class="item7">7</div>
<div class="item8">8</div>
<div class="item9">9</div>
</div>
Example 1: Making x Items per row using CSS Grid
To accomplish this, let’s add CSS to the grid container and the items:
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
gap: 10px;
background-color: #04AA6D;
padding: 10px;
}
.grid-container > div {
background-color: white;
text-align: center;
padding: 20px 0;
font-size: 30px;
}
grid-template-columns: auto auto auto;
is responsible for making 3 items per row. Instead of auto, you can provide a specific width or percentage for each column like.
For example: grid-template-columns: 30% 20% 20%;
will give the result:
Example 2: Item taking x rows and columns
.item1 {
grid-row-start: 1;
grid-row-end: 3;
}
There item 1 takes two rows. Similarly, here item 1 takes 3 columns.
.item1 {
grid-column-start: 1;
grid-column-end: 4;
}
Example 3: Grid Gaps
We have already assigned the gap of 10px on the grid container. But, there are specific properties as well:
- column-gap
- row-gap
- gap
.grid-container {
column-gap: 100px;
row-gap: 10px;
}
That’s all the basics we’ll need.
Example 4
.item1 {
grid-row-start: 1;
grid-row-end: 3;
}
.item4, .item9 {
grid-column-start: 2;
grid-column-end: 4;
}
Real-Life Work
I have learned the CSS Grid because I have to accomplish something similar in my work. That is why I like the “Learning by doing!” approach.
I hope this article helps! If you’re stuck, feel free to ask questions in the comments.