CSS Grid Basics
CSS Grid is a layout system designed specifically for creating two-dimensional layouts. It allows you to arrange content into rows and columns with precision and flexibility.
1. Enabling Grid
To start using grid, apply display: grid;
to the container element:
.container {
display: grid;
}
2. Defining Columns and Rows
Use grid-template-columns
and grid-template-rows
to define structure:
.container {
display: grid;
grid-template-columns: 200px 1fr 100px;
grid-template-rows: auto 1fr auto;
}
3. Adding Gaps
Use gap
(or row-gap
and column-gap
) to create spacing between grid items:
.container {
display: grid;
gap: 20px;
}
4. Placing Items
You can place items in specific grid areas using line numbers:
.item {
grid-column: 1 / 3; /* spans column 1 to 2 */
grid-row: 2 / 4; /* spans row 2 to 3 */
}
5. Repeat Syntax
Use repeat()
to simplify repeated values:
.container {
grid-template-columns: repeat(3, 1fr);
}
6. Auto-fit and Auto-fill
Create responsive grids with flexible columns:
.container {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
Conclusion
CSS Grid offers powerful tools for building responsive and complex layouts with ease. By learning the basics, you're ready to start creating structured, flexible grid designs for modern web interfaces.