Set areas within the grid layout in CSS

The CSS grid-template-areas property allows you to define named grid areas within a grid layout, making it easy to position grid items by name rather than line numbers. This property works with grid-area to create intuitive and maintainable grid layouts.

Syntax

.grid-container {
    display: grid;
    grid-template-areas: 
        "area-name area-name . . ."
        "area-name area-name . . .";
}

.grid-item {
    grid-area: area-name;
}

Key Properties

Property Description
grid-template-areas Defines named grid areas using strings
grid-area Assigns a grid item to a named area
grid-gap Sets spacing between grid rows and columns

Example: Named Grid Areas

The following example creates a grid with a named area called "newArea" that spans 2x2 cells −

<!DOCTYPE html>
<html>
<head>
<style>
    .grid-container {
        display: grid;
        grid-template-areas:
            'newArea newArea . . .'
            'newArea newArea . . .';
        grid-gap: 5px;
        background-color: #2196F3;
        padding: 10px;
    }
    
    .demo {
        grid-area: newArea;
        background-color: #FF5722;
        color: white;
        font-weight: bold;
    }
    
    .grid-container > div {
        background-color: #FFC107;
        text-align: center;
        padding: 20px;
        font-size: 18px;
    }
</style>
</head>
<body>
    <div class="grid-container">
        <div class="demo">Named Area (newArea)</div>
        <div>Item 2</div>
        <div>Item 3</div>
        <div>Item 4</div>
        <div>Item 5</div>
        <div>Item 6</div>
        <div>Item 7</div>
    </div>
</body>
</html>
A grid layout with a blue background appears. The first item (red) spans a 2x2 area in the top-left corner labeled "Named Area (newArea)". The remaining yellow items fill the other grid positions automatically.

Understanding Grid Template Areas

In the grid-template-areas property, each string represents a row, and each word in the string represents a column. The dot (.) represents an empty cell. Grid items are assigned to areas using the grid-area property with the corresponding area name.

Conclusion

The grid-template-areas property provides an intuitive way to create complex grid layouts using named areas. This approach makes your CSS more readable and easier to maintain than using line-based positioning.

Updated on: 2026-03-15T13:39:36+05:30

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements