Awesome! Let’s dive into a powerful layout tool every frontend developer must know: CSS Grid.
๐ LESSON 11: Introduction to CSS Grid
โ Learning Goals:
- Understand the CSS Grid layout system
- Learn the key terminology: grid container, items, rows, columns
- Create responsive, 2D layouts using Grid
- Combine Grid with Flexbox where needed
๐งพ Lesson Content (Text for Website)
๐ณ What Is CSS Grid?
CSS Grid is a layout system designed for 2D layouts โ both rows and columns.
It gives you full control over spacing, alignment, and responsiveness.
Use Flexbox for 1D layout (row or column), and Grid for 2D layout (row + column).
๐งฉ Grid Terminology
Term | Description |
---|---|
Grid Container | The parent element that defines the grid layout |
Grid Item | The children of the grid container |
Grid Lines | The dividing lines between rows and columns |
Grid Track | A row or column |
Grid Area | A group of cells you can name and use |
๐งช Basic Grid Example
<style>
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */
gap: 20px;
}
.grid-item {
background: #ffe082;
padding: 20px;
text-align: center;
border-radius: 8px;
}
</style>
<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>
๐จ This creates 3 equal-width items in one row with gaps!
๐ Other Grid Options
๐ธ Fixed Width Columns
grid-template-columns: 200px 1fr 100px;
- First column: 200px
- Second column: takes remaining space
- Third column: 100px
๐ธ Repeat Syntax
grid-template-columns: repeat(3, 1fr);
= same as 1fr 1fr 1fr
๐ธ Responsive with auto-fit
and minmax
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
๐ Automatically adjusts number of columns based on screen width!
๐ฏ Grid Item Placement
.item {
grid-column: 1 / 3; /* spans columns 1 to 2 */
grid-row: 1 / 2;
}
Use this to control how wide or tall each item is within the grid.
๐งช Practice Layout: Responsive Cards Grid
<style>
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 20px;
padding: 30px;
}
.card {
background: #fff3e0;
padding: 20px;
border-radius: 6px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
</style>
<div class="card-grid">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
<div class="card">Card 4</div>
</div>
โ Fully responsive grid cards using auto-fit and minmax.
๐ Summary
- CSS Grid = powerful for 2D layouts
- Use
grid-template-columns
,gap
, andrepeat()
- Combine with media queries for max control
- Best used for galleries, cards, dashboards, complex page layouts
๐ Next Lesson:
๐ Lesson 12: Project โ Create a CSS Grid Photo Gallery
25
One Response