CSS Grid Layout
💻 CSSBuild two-dimensional layouts with grid template columns, rows and gaps.
CSS Grid arranges items in rows and columns at the same time. It is ideal for page layouts, galleries and dashboards.
- Create a grid container.
- Define columns and rows.
- Place items across tracks.
A Basic Grid
Set display: grid on the parent and define columns with grid-template-columns. The gap property spaces the items.
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}
.gallery img {
width: 100%;
height: 200px;
object-fit: cover;
}Fractional Units
1fr means one fraction of the available space. repeat(3, 1fr) creates three equal columns. Mixed tracks such as 240px 1fr give a fixed sidebar and a flexible main area.
Placing Items
Items can span several columns or rows. Use grid-column: span 2 for a wide card, or name lines and place items explicitly.
.featured {
grid-column: span 2;
}
.layout {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
gap: 24px;
}Grid or Flexbox?
Use Grid when you need rows and columns together. Use Flexbox when items flow mainly in one direction, such as a navigation bar or a row of buttons.
Practice
- Build a three-column photo gallery with a 16px gap.
- Make the first card span two columns.
- Create a page layout with a fixed sidebar and a flexible main area.
Hands-on exercise
Create a grid of six cards.
1. Use three equal columns on wide screens.
2. Add a 20px gap.
3. Make the first card span two columns.
4. Give each card a border and padding.
Recap
Grid controls rows and columns together. Use fractional units, gaps and spanning to build clean layouts.
Example
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}
.gallery img {
width: 100%;
height: 200px;
object-fit: cover;
}
Exercises
1. Use three equal columns on wide screens.
2. Add a 20px gap.
3. Make the first card span two columns.
4. Give each card a border and padding.
Expected Output
Six cards in a three-column grid with the first card twice as wide.
Lesson Nav
CSS Course
0/9 lessons completed
- 1 How to Add CSS to HTML Tutorial
- 2 Colors, Fonts, and Text Tutorial
- 3 The Box Model Tutorial
- 4 Flexbox Layout Tutorial
- 5 Build a Landing Page Project
- 6 CSS Grid Layout Tutorial
- 7 Responsive Design with Media Queries Tutorial
- 8 Transitions, Transforms and Animation Tutorial
- 9 Project: A Responsive Portfolio Project