🧩 Day 18 — CSS Grid: Two-Dimensional Layouts
Welcome to Day 18! If Flexbox is about arranging items in one direction, **CSS Grid** is about controlling entire two-dimensional layouts — rows and columns together. It’s perfect for building dashboards, galleries, multi-column sites, and magazine-style pages. By mastering Grid, you’ll gain precise, responsive control of every section on a webpage.
📘 1️⃣ What Is CSS Grid?
CSS Grid is a layout system that lets you divide a container into rows and columns. You define grid tracks, and then place child elements (grid items) into specific cells using clean, declarative syntax.
.container {
display: grid;
grid-template-columns: 200px 200px 200px;
grid-template-rows: auto auto;
gap: 10px;
}
🧱 2️⃣ Creating Your First Grid
<div class="grid-container"> <div>Box 1</div> <div>Box 2</div> <div>Box 3</div> <div>Box 4</div> </div>CSS:
.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 20px;
}
.grid-container div {
background:#9c27b0;
color:#fff;
padding:20px;
border-radius:6px;
}
🧩 3️⃣ Grid Units and Fractions
The fr (fraction) unit divides remaining space proportionally.
Example: 1fr 1fr 2fr means the last column gets twice the width of each of the others.
🎯 4️⃣ Implicit vs Explicit Grid
- Explicit grid — defined by
grid-template-columnsandrows. - Implicit grid — extra tracks auto-created when needed; size controlled with
grid-auto-rows.
📐 5️⃣ Grid Gap (Spacing)
.grid-container {
gap: 15px; /* shorthand for row-gap + column-gap */
}
🧭 6️⃣ Placing Items Manually
.item1 {
grid-column: 1 / 3;
grid-row: 1 / 2;
}
This makes the first item stretch across two columns and one row.
💡 7️⃣ Named Grid Areas
You can assign names to specific regions of a grid — very useful for page templates.
.grid-container {
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 200px 1fr;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
⚙️ 8️⃣ Responsive Grids with auto-fit and minmax()
.grid-container {
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
This automatically creates as many columns as fit in the available width — perfect for responsive galleries.
🧠 9️⃣ Practice Task
- Build a 3×3 grid of colored boxes with equal gaps.
- Make the first box span across two columns.
- Use
grid-template-areasto design a layout with header, sidebar, main, footer. - Try
auto-fit minmax()to make it responsive.
🧮 Mini Quiz
- Q1: What does
frrepresent in CSS Grid? - Q2: Difference between explicit and implicit grids?
- Q3: How do you create responsive grids automatically?
🎯 Summary
You’ve learned how to use CSS Grid to build two-dimensional layouts with precision. Combine Grid with Flexbox for complex, responsive designs. Next, you’ll add life to these layouts through animations and transformations in **Day 19**.
Comments
Post a Comment