What is CSS Grid?
CSS Grid is a layout system that lets you build two-dimensional layouts with rows and columns. Think of it like a spreadsheet for your webpage: you define a grid structure, then place content into the cells.
Before CSS Grid, developers used floats, positioning, and Flexbox to create layouts. These methods work, but they were never designed specifically for page layouts. CSS Grid was built from the ground up to solve layout problems, making it more intuitive and powerful.
Why Use CSS Grid?
1. Two-Dimensional Layouts
Unlike Flexbox, which is one-dimensional, CSS Grid lets you control both rows and columns at the same time. This makes complex layouts much easier to build and maintain.
2. Less Code
What used to take dozens of lines of CSS with floats or positioning can now be done in just a few lines with Grid. Your code becomes cleaner and easier to understand.
3. Responsive by Design
CSS Grid has built-in features for responsive design. You can create layouts that automatically adapt to different screen sizes without writing complex media queries.
The Basic Concept
Every CSS Grid layout has two key parts:
- Grid Container: The parent element that holds the grid (set with
display: grid) - Grid Items: The children elements that go inside the grid cells
display: grid on a container, all its direct children automatically become grid items.
You do not need to do anything special to the children.
Your First Grid
Here is the simplest possible grid:
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
This creates:
- A grid container (
display: grid) - Three equal columns (
1fr 1fr 1fr) - 20px spacing between items (
gap: 20px)
Common Use Cases
CSS Grid is well suited for:
- Page Layouts: Header, sidebar, content, footer arrangements
- Card Grids: Product listings, image galleries, blog post grids
- Dashboards: Multi-panel admin interfaces
- Forms: Aligned labels and inputs
- Complex Designs: Magazine-style layouts with overlapping elements
Grid vs. Other Methods
When to use Grid: When you need to control both rows and columns, or when you are building a page layout.
When to use Flexbox: When you are arranging items in a single direction, like a navigation bar or a row of buttons.
The truth: You will often use both. Grid for the overall page structure, Flexbox for components within the grid.
Browser Support
CSS Grid is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge, and works in over 96% of browsers worldwide. For older browsers such as IE11, you will need fallback layouts, but for most projects, Grid is safe to use today.
Next Steps
Now that you understand what CSS Grid is and why it is useful, you are ready to learn how to actually use it. In the next lesson, we will cover rows, columns, and how to create your first practical grid layout.