CSS Grid Layout
CSS Grid Layout is a powerful two-dimensional layout system designed for the web. It allows developers to easily build complex layouts by controlling both rows and columns simultaneously without relying on floats or complex positioning hacks.
Mastering CSS Grid provides fine-grained control over alignment, spacing, and responsive design, making modern frontend development cleaner and more efficient.
Creating a Grid Container
To start using grid layout, define a container element with display: grid or display: inline-grid. This transforms all direct children of the container into grid items.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto;
gap: 20px;
}
The fr unit represents a fraction of the available space in the grid container, allowing flexible and responsive sizing.
Placing Grid Items
Grid items can span multiple columns or rows using properties like grid-column and grid-row, giving you complete flexibility over placement.
.item-featured {
grid-column: 1 / span 3;
grid-row: 1;
}
This positions the featured item across the entire top row of a three-column grid layout.
Responsive Grids with Auto-Fit
You can create responsive layouts without media queries by combining grid-template-columns with auto-fit and minmax().
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 16px;
}
The browser automatically fits as many columns as possible based on the minimum width of 250px, wrapping items neatly onto new rows on smaller screens.
Summary
CSS Grid Layout transforms how web layouts are structured by offering native two-dimensional control. Using fractional units, explicit templates, and auto-fit techniques enables robust, clean, and highly responsive modern user interfaces.