Usage of CSS grid property

The CSS grid property is a shorthand property that allows you to set multiple grid-related properties in a single declaration. It can be used to define grid-template-rows, grid-template-columns, grid-template-areas, grid-auto-rows, grid-auto-columns, and grid-auto-flow properties all at once.

Syntax

selector {
    grid: <grid-template-rows> / <grid-template-columns>;
    /* or */
    grid: <grid-template>;
    /* or */
    grid: <grid-auto-flow> <grid-auto-rows> / <grid-auto-columns>;
}

Example: Basic Grid Layout

The following example creates a grid with one row of 100px height and two equal-width columns −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        display: grid;
        grid: 100px / auto auto;
        grid-gap: 10px;
        background-color: #ff6b6b;
        padding: 10px;
        max-width: 400px;
    }
    
    .container > div {
        background-color: #ffd93d;
        text-align: center;
        padding: 10px 0;
        font-size: 20px;
        border-radius: 5px;
    }
</style>
</head>
<body>
    <div class="container">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
    </div>
</body>
</html>
A red container with yellow grid items arranged in a 2-column layout. Items 1-2 appear in the first row (100px height), items 3-4 in the second row, and items 5-6 in the third row. Each item has rounded corners and is centered with 10px gaps between them.

Example: Multiple Rows and Columns

This example creates a 2x3 grid with specific row and column sizes −

<!DOCTYPE html>
<html>
<head>
<style>
    .grid-container {
        display: grid;
        grid: 80px 120px / 1fr 2fr 1fr;
        grid-gap: 15px;
        background-color: #74b9ff;
        padding: 15px;
        max-width: 500px;
    }
    
    .grid-container > div {
        background-color: #a29bfe;
        color: white;
        text-align: center;
        padding: 20px;
        font-size: 18px;
        border-radius: 8px;
    }
</style>
</head>
<body>
    <div class="grid-container">
        <div>Item 1</div>
        <div>Item 2</div>
        <div>Item 3</div>
        <div>Item 4</div>
        <div>Item 5</div>
        <div>Item 6</div>
    </div>
</body>
</html>
A blue container with purple grid items arranged in 2 rows and 3 columns. The first row is 80px tall, the second row is 120px tall. The middle column is twice as wide as the outer columns. Items are evenly distributed with 15px gaps and rounded corners.

Conclusion

The grid property provides a convenient shorthand for defining grid layouts. It's particularly useful for creating responsive layouts with precise control over row and column sizing.

Updated on: 2026-03-15T13:14:21+05:30

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements