Welcome to our deep dive into CSS Grid Items! This tutorial is designed to help both beginners and intermediates understand the powerful world of CSS Grid. Let's get started! šÆ
CSS Grid allows us to design complex layouts with ease. A Grid contains Grid Containers and Grid Items. Grid Items are the content areas within the Grid Container that are sized, positioned, and aligned using the Grid lines.
/* Grid container */
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
grid-template-rows: auto auto;
gap: 10px;
}
/* Grid item */
.grid-item {
background-color: #f2f2f2;
padding: 20px;
text-align: center;
}š” Pro Tip: Always remember to set display: grid on the container to turn it into a Grid Container and define the number of columns and rows using the grid-template-columns and grid-template-rows properties.
Grid Items are automatically created based on the number of rows and columns defined. They can be positioned using the grid-column and grid-row properties.
/* Positioning a grid item */
.grid-item:nth-child(3) {
grid-column: span 2;
grid-row: span 2;
}Grid Items can be sized using the grid-column-start, grid-column-end, grid-row-start, and grid-row-end properties.
/* Sizing a grid item */
.grid-item-1 {
grid-column-start: 1;
grid-column-end: 3;
grid-row-start: 1;
grid-row-end: 3;
}Grid Items can be aligned using the align-self property.
/* Aligning a grid item */
.grid-item-1 {
align-self: center;
}Let's build a simple 3x3 grid with alternating colors.
<div class="grid-container">
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
</div>.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 10px;
}
.grid-item:nth-child(odd) {
background-color: #f2f2f2;
}
.grid-item:nth-child(even) {
background-color: #cccccc;
}Happy coding! š If you're enjoying this tutorial, don't forget to share it with your friends. Stay tuned for more lessons on CSS Grid! š”