Align the grid inside the container using CSS

CSS Grid provides powerful alignment properties to position the entire grid inside its container. The justify-content property aligns the grid horizontally, while align-content aligns it vertically within the container.

Syntax

.grid-container {
    justify-content: value;  /* Horizontal alignment */
    align-content: value;    /* Vertical alignment */
}

Possible Values

Value Description
start Aligns grid to the start of the container
center Centers the grid in the container
end Aligns grid to the end of the container
space-between Distributes space between grid tracks
space-around Distributes space around grid tracks
space-evenly Distributes space evenly between and around tracks

Example: Horizontal Grid Alignment

The following example demonstrates how to align a grid horizontally using justify-content

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        display: grid;
        background-color: lightgray;
        grid-template-columns: 100px 100px;
        grid-template-rows: 80px 80px 80px;
        justify-content: space-evenly;
        padding: 20px;
        gap: 15px;
        height: 400px;
    }
    .container > div {
        background-color: #4CAF50;
        border: 2px solid #333;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        font-weight: bold;
    }
</style>
</head>
<body>
    <h2>Grid Alignment Example</h2>
    <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 light gray container with six green numbered boxes (1-6) arranged in a 2x3 grid. The grid is horizontally centered with equal spacing between and around the columns due to space-evenly alignment.

Conclusion

The justify-content and align-content properties provide flexible control over grid positioning within containers. Use these properties to create responsive layouts with proper spacing and alignment.

Updated on: 2026-03-15T12:58:07+05:30

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements