CSS
Responsive Grid Columns with `fr` Units
Create dynamic and responsive grid layouts where column widths automatically adjust using the flexible `fr` unit in CSS Grid, adapting to various screen sizes without complex media queries.
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* Example: three columns, middle one is twice as wide */
gap: 1rem;
}
/* For a more responsive approach, combine with media queries or minmax */
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr; /* Stack columns on smaller screens */
}
}
/* Another example: Sidebar + Main Content */
.layout-sidebar {
display: grid;
grid-template-columns: 200px 1fr; /* Fixed sidebar, fluid content */
gap: 1.5rem;
}
@media (max-width: 768px) {
.layout-sidebar {
grid-template-columns: 1fr;
}
.sidebar {
grid-row: 2; /* Move sidebar below content on mobile */
}
}
How it works: This snippet demonstrates how to create responsive grid layouts using the `fr` unit. `fr` (fractional unit) represents a portion of the available space in the grid container, allowing for flexible column sizing. For example, `1fr 2fr 1fr` creates three columns where the middle column is twice as wide as the outer two. The example also shows how to use media queries to adapt the column structure for different screen sizes, such as stacking columns vertically on smaller devices, or creating a fixed-width sidebar with a fluid content area that reorders on mobile.