Premium CSS Course

CSS Grid

CSS Grid Layout is a two-dimensional layout system for the web. It enables you to design web pages with rows and columns, giving you control over both horizontal and vertical positioning. With CSS Grid, you can create complex layouts with ease and flexibility.

What is CSS Grid?

CSS Grid allows you to divide a webpage into a grid of rows and columns. You can control the placement of elements inside the grid and define how they span across different grid areas. This is especially useful for creating responsive, multi-column layouts without the need for floats or complex CSS techniques.

Creating a Grid Container

To create a grid layout, you need to define a grid container. This is done by setting the parent element’s display property to grid.


        .container {
            display: grid;
        }
    

Once the grid container is set, its child elements (grid items) will automatically be placed in the grid.

Grid Container Properties

Here are some important properties for configuring a grid container:

Grid Item Properties

CSS Grid also provides properties for controlling the positioning of grid items within the grid container.

Example of Grid Layout

Here’s an example of a simple grid layout with a header, sidebar, content area, and footer:


        .container {
            display: grid;
            grid-template-columns: 1fr 3fr;
            grid-template-rows: auto 1fr auto;
            gap: 20px;
            grid-template-areas:
                "header header"
                "sidebar content"
                "footer footer";
        }

        .header {
            grid-area: header;
            background-color: #f0f0f0;
        }

        .sidebar {
            grid-area: sidebar;
            background-color: #d0d0d0;
        }

        .content {
            grid-area: content;
            background-color: #e0e0e0;
        }

        .footer {
            grid-area: footer;
            background-color: #f0f0f0;
        }
    

This creates a layout where the header spans the full width of the grid, the sidebar takes the left column, and the content fills the remaining space. The footer spans the full width at the bottom.

Best Practices for Using CSS Grid