DEV Community

Lokesh
Lokesh

Posted on

CSS Grid

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>
Enter fullscreen mode Exit fullscreen mode

CSS:

.container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 10px;
}
Enter fullscreen mode Exit fullscreen mode

Here:

  • display: grid enables CSS Grid.
  • grid-template-columns creates three columns.
  • 1fr represents one fraction of the available space.
  • gap adds 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;
}
Enter fullscreen mode Exit fullscreen mode

2. grid-template-columns

This property defines the number and size of columns.

.container {
    display: grid;
    grid-template-columns: 200px 200px 200px;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

This defines two rows, each 100px tall.

4. gap

The gap property adds space between rows and columns.

.container {
    display: grid;
    gap: 20px;
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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)