What Is CSS Grid?
CSS Grid is a CSS layout system that allows us to arrange elements in rows and columns.
For example, if we want to display six product cards in a grid, CSS Grid makes it easy to organize them.
How to Use CSS Grid?
To use CSS Grid, we need to apply display: grid to a parent element.
HTML:
<div class="container">
<div>Box 1</div>
<div>Box 2</div>
<div>Box 3</div>
<div>Box 4</div>
<div>Box 5</div>
<div>Box 6</div>
</div>
CSS:
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 10px;
}
Here:
-
display: gridenables CSS Grid. -
grid-template-columnscreates three columns. -
1frrepresents one fraction of the available space. -
gapadds space between the boxes.
The six boxes will be arranged in three columns and two rows.
Important CSS Grid Properties
1. display: grid
This property enables Grid layout for the child elements of a container.
.container {
display: grid;
}
2. grid-template-columns
This property defines the number and size of columns.
.container {
display: grid;
grid-template-columns: 200px 200px 200px;
}
This creates three columns, each 200px wide.
We can also use 1fr to divide the available space into equal fractions.
3. grid-template-rows
This property defines the size of rows.
.container {
display: grid;
grid-template-rows: 100px 100px;
}
This defines two rows, each 100px tall.
4. gap
The gap property adds space between rows and columns.
.container {
display: grid;
gap: 20px;
}
This creates a 20px gap between the grid items.
5. repeat()
The repeat() function helps us write shorter CSS code when columns or rows have the same size.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
This creates three equal-width columns without repeating 1fr manually.
Where Is CSS Grid Used?
CSS Grid is commonly used to create:
- Product card layouts
- Image galleries
- Website page layouts
- Portfolio sections
- Dashboard layouts
It is especially useful when we need to arrange elements in both rows and columns.
CSS Grid vs Flexbox
Both CSS Grid and Flexbox help us arrange elements, but they have different strengths.
- Flexbox: Best suited for arranging items in one direction at a time, either a row or a column.
- CSS Grid: Best suited for layouts that need control over both rows and columns together.
Both are useful, and we can even use them together in the same project.
Top comments (0)