CSS Grid 🍴
What You'll Learn
- Create two-dimensional grid layouts
- Use grid-template-columns and grid-template-rows
- Build a responsive card grid
Grid vs Flexbox
Flexbox is great for one-dimensional layouts (a row OR a column). CSS Grid is designed for two-dimensional layouts (rows AND columns together). Think of it like a spreadsheet.
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */
grid-template-rows: auto; /* rows size to content */
gap: 1.5rem; /* space between cells */
}The fr unit means "fraction of available space." 1fr 1fr 1fr = three equal columns.
Shorthand with repeat()
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr); /* same as 1fr 1fr 1fr */
gap: 2rem;
}
/* Make it responsive: */
.grid-responsive {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
}grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)) is the magic line for responsive grids. It automatically adjusts how many columns fit based on screen width!
Spanning Multiple Cells
.featured-card {
grid-column: span 2; /* takes up 2 column slots */
}
.full-width {
grid-column: 1 / -1; /* spans ALL columns */
}Create 6 card divs. Put them in a grid container with repeat(auto-fit, minmax(280px, 1fr)) and gap: 1.5rem. Style each card with padding, border, border-radius, and a background color. Resize your browser window and watch the grid reflow!
What does 1fr mean in CSS Grid?
What does grid-column: span 2 do?
What is the key advantage of CSS Grid over Flexbox?