CSS Grid
CSS Grid is a powerful layout system that lets us work with two-dimensional grids, allowing elements to be arranged more precisely and flexibly.
The basics of Grid
Grid allows us to create columns and rows and place elements into these cells. The basic settings can be defined with grid-template-columns, grid-template-rows, and gap properties.
| Property | Description |
|---|---|
| display: grid | Enables Grid layout on the selected element. |
| grid-template-columns | Defines the number and size of columns. |
| grid-template-rows | Defines the number and size of rows. |
| gap | Specifies the spacing between columns and rows. |
Practical example
In the example below, we create a three-column grid where elements automatically align with the cells.
With grid-template-columns: 1fr 1fr 1fr, we create three equal columns, and with gap we add spacing between the elements.
Grid areas and named regions
With the grid-template-areas property, we can assign names to specific areas of the grid. This makes the layout more readable and maintainable.
In the example below, the header, main content, and footer are defined as separate grid areas.
Responsive grid using repeat() and auto-fit/auto-fill
The combination of repeat(), auto-fit, and auto-fill dynamically fills the available space, so the grid automatically adapts to the screen size.
In the example below, the grid columns automatically adapt to the screen size.
Tips for using Grid
The big advantage of Grid is that it handles complex layouts easily. Row and column sizes can change dynamically, making it excellent for creating responsive layouts.
- Use fr (fractional unit) for flexible sizing of columns and rows.
- With grid-template-areas, you can make the code more readable and maintainable.
- Combining Grid and Flexbox provides even more flexible and creative layouts.
✨ Ask Lara — your AI study partner
Unlock personalized learning support. Lara can explain lessons, summarize topics, and answer your study questions — available from the Go plan and above.
Lara helps you learn faster — exclusive to ReadyTools Go, Plus, and Max members.
