CSS

Build a Dynamic Grid Layout with Custom Row/Column Definitions

Master CSS Grid by defining custom rows and columns using `grid-template-columns` and `grid-template-rows`. Perfect for structured layouts like dashboards and forms.

.grid-container {
    display: grid;
    grid-template-columns: 1fr 3fr; /* Two columns: 1 unit and 3 units wide */
    grid-template-rows: auto 1fr auto; /* Header, main content, footer rows */
    gap: 15px; /* Spacing between grid items */
    min-height: 100vh; /* Example: Full viewport height */
    background-color: #f9f9f9;
    padding: 15px;
}

.header {
    grid-column: 1 / -1; /* Spans all columns */
    background-color: #e0e0e0;
    padding: 10px;
}

.sidebar {
    grid-column: 1; /* Stays in the first column */
    grid-row: 2;   /* Stays in the second row (main content row) */
    background-color: #d0d0d0;
    padding: 10px;
}

.main {
    grid-column: 2; /* Stays in the second column */
    grid-row: 2;   /* Stays in the second row (main content row) */
    background-color: #c0c0c0;
    padding: 10px;
}

.footer {
    grid-column: 1 / -1; /* Spans all columns */
    background-color: #e0e0e0;
    padding: 10px;
}

/* Basic responsiveness for smaller screens */
@media (max-width: 768px) {
    .grid-container {
        grid-template-columns: 1fr; /* Single column layout */
        grid-template-rows: auto auto 1fr auto; /* Header, Sidebar, Main, Footer */
    }
    .header, .sidebar, .main, .footer {
        grid-column: 1; /* All items span the single column */
    }
    .sidebar {
        grid-row: 2; /* Sidebar becomes second item */
    }
    .main {
        grid-row: 3; /* Main content becomes third item */
    }
    .footer {
        grid-row: 4; /* Footer becomes fourth item */
    }
}
How it works: This snippet illustrates how to create a structured grid layout using CSS Grid with explicit `grid-template-columns` and `grid-template-rows`. It defines specific column and row sizes using `fr` units (fractional units) and `auto`. Individual grid items are then placed using `grid-column` and `grid-row` properties to assign them to specific grid lines. A basic media query is included to adapt the layout to a single-column stack on smaller screens, demonstrating responsive design with Grid.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs