CSSLesson 8 of 10Jump to practice
CSS grid
Build layouts with rows and columns at the same time.
Flexbox works in one direction at a time. Grid works in two: you define columns and rows, and place items into the cells.
Columns
Put display: grid on the parent and describe the columns with grid-template-columns.
<!DOCTYPE html>
<html>
<head>
<style>
.gallery {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 10px;
font-family: sans-serif;
}
.gallery div { background: #cfeee9; padding: 20px; text-align: center; }
</style>
</head>
<body>
<div class="gallery">
<div>1</div><div>2</div><div>3</div>
<div>4</div><div>5</div><div>6</div>
</div>
</body>
</html>The items fill the cells left to right, then start a new row. You didn’t have to say how many rows.
The fr unit and repeat()
fris a fraction of the leftover space.1fr 2frmakes the second column twice as wide.repeat(3, 1fr)is short for1fr 1fr 1fr.- You can mix units:
200px 1fris a fixed sidebar and a flexible main column.
<!DOCTYPE html>
<html>
<head>
<style>
.page {
display: grid;
grid-template-columns: 160px 1fr;
gap: 10px;
font-family: sans-serif;
}
header, footer { grid-column: span 2; background: #123b3c; color: white; padding: 12px; }
aside { background: #fff7e0; padding: 12px; }
main { background: #eef3f2; padding: 12px; min-height: 100px; }
</style>
</head>
<body>
<div class="page">
<header>Header (spans 2 columns)</header>
<aside>Sidebar</aside>
<main>Main content</main>
<footer>Footer (spans 2 columns)</footer>
</div>
</body>
</html>grid-column: span 2 makes the header and footer stretch across both columns.
Responsive without media queries
This one line makes as many columns as fit, each at least 140px wide:
<!DOCTYPE html>
<html>
<head>
<style>
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
gap: 10px;
font-family: sans-serif;
}
.cards div { background: #ffe08a; padding: 24px 12px; border-radius: 8px; text-align: center; }
</style>
</head>
<body>
<div class="cards">
<div>Chicago</div><div>Seattle</div><div>Denver</div>
<div>Boston</div><div>Austin</div><div>Miami</div>
</div>
</body>
</html>Open it in the editor and drag the window narrower. The number of columns changes on its own.
Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Turn on grid layout for the container.
.gallery { display: ; }Exercise 2Solved
Make three equal columns without typing
1frthree times..gallery { display: grid; grid-template-columns: (3, 1fr); }Exercise 3Solved
Make this item stretch across two columns.
.wide { grid-column: 2; }
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.