Create A Grid Layout With CSS

This blog post will explain how to use css3 to create a grid layout for a web page.

Here is the css code that is needed to make it work. Three classes within the css file are used to determine how many columns are on each row. They are row-container1, row-container2, and row-container3. The number of columns on each row can be from one to three. The cell class will style each column in each row.

.row-container1
{
display: grid;
grid-template-columns: repeat(1, 1fr);
gap: 10px;
padding:5px;
}
 
.row-container2
{
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
padding:5px;
}

.row-container3
{
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
padding:5px;
}

.cell
{
background-color: #f1f1f1;
padding: 10px;
text-align: center;
}

Here is the html code that is needed to make it work. Within the body section, a main section is declared. The code goes in the main section. There are three div elements that are declared that use the row-container classes. In those div elements, there are one to three div elements that use the cell class. That creates the grid layout with one to three columns on each row.

<main>
<div class="row-container1">
<div class="cell"><p>Item</p></div>
</div>
<div class="row-container2">
<div class="cell"><p>Item</p></div>
<div class="cell"><p>Item</p></div>
</div>
<div class="row-container3">
<div class="cell"><p>Item</p></div>
<div class="cell"><p>Item</p></div>
<div class="cell"><p>Item</p></div>
</div>
</main>

Leave a Reply