Introduction
CSS Grid Layout is a two-dimensional layout system that allows developers to create complex and responsive web designs easily. Unlike Flexbox, which works in one dimension (row or column), CSS Grid enables control over both rows and columns simultaneously.
1. What is CSS Grid?
CSS Grid provides a way to create structured layouts without relying on floats or positioning.
Benefits of CSS Grid:
- Controls both rows and columns.
- Eliminates the need for complicated CSS hacks.
- Simplifies responsive design.
2. Setting Up a Grid Container
To use CSS Grid, set the display
property to grid
.
Example:
.container {
display: grid;
grid-template-columns: 200px 200px 200px;
grid-template-rows: 100px 100px;
gap: 10px;
}
.item {
background-color: lightblue;
padding: 20px;
text-align: center;
}
CSS<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>
HTML3. Grid Properties
3.1 grid-template-columns
& grid-template-rows
Defines column and row sizes.
.container {
grid-template-columns: 100px 200px auto;
grid-template-rows: 100px auto 50px;
}
CSS3.2 gap
Adds space between grid items.
.container {
gap: 20px;
}
CSS3.3 grid-column
& grid-row
Controls item placement.
.item {
grid-column: 1 / 3;
grid-row: 2 / 4;
}
CSS4. Creating Responsive Grids
Use repeat()
and minmax()
for flexible layouts.
.container {
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}
CSS5. Grid Auto-Placement
CSS Grid automatically places items if not explicitly positioned.
.container {
grid-template-columns: repeat(3, 1fr);
}
CSS6. Aligning Grid Items
6.1 justify-items
& align-items
.container {
justify-items: center; /* start, end, stretch */
align-items: center; /* start, end, stretch */
}
CSS6.2 justify-content
& align-content
.container {
justify-content: space-between; /* center, space-around, space-evenly */
align-content: space-evenly;
}
CSS7. Grid Layout Examples
7.1 Simple Card Layout
.container {
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
CSS7.2 Sidebar Layout
.container {
grid-template-columns: 1fr 3fr;
}
CSSConclusion
CSS Grid makes creating responsive layouts simple and efficient. Mastering its properties will help you design advanced web layouts with ease.