CSS Display Grid: Mastering 2D Layouts
Flexbox was built for 1-dimensional layouts (a row or a column). CSS Grid is the ultimate tool for 2-dimensional layouts (rows AND columns simultaneously). It radically changes how we structure UI.
The Foundation: The Grid Container
Just like Flexbox, you start by setting display: grid; on a parent element. This instantly turns all direct children into "grid items".
By default, a grid will only have one column. To make it useful, we define "tracks" (columns and rows) using grid-template-columns and grid-template-rows.
Fluid Sizing: The `fr` Unit
Grid introduces a powerful new unit: the fraction (fr). It represents a fraction of the available space in the grid container.
Instead of calculating percentages, you can write grid-template-columns: 1fr 2fr 1fr;. The browser dynamically calculates the pixels, ensuring the second column is exactly twice as large as the others, automatically adjusting for any gap.
Placing Items: Spanning
One of the most complex things in legacy CSS was making an element break out of its standard width. With Grid, it's trivial. We use grid lines.
- Grid Lines: In a 3-column grid, there are 4 vertical lines. Line 1 is the start, Line 4 is the end.
- grid-column: Using
grid-column: 1 / 3;tells an item to start at line 1 and end at line 3, effectively spanning 2 columns. Alternatively, usegrid-column: span 2;.
View Architecture Tip+
Flexbox vs Grid: When to use which? Rule of thumb: Use Flexbox when you care about the flow of content in a single direction (like a navigation bar). Use Grid when you need a rigid, macro-level structure (like a full page layout, dashboard, or photo gallery). They work best when combined!
❓ Frequently Asked Questions
¿Cuál es la diferencia entre CSS Flexbox y CSS Grid?
Flexbox: Es unidimensional. Diseñado para alinear elementos en una sola fila o una sola columna. El contenido dicta el tamaño.
Grid: Es bidimensional. Puedes controlar filas y columnas simultáneamente. El layout (la estructura) dicta el tamaño del contenido.
¿Qué hace exactamente la función repeat()?
Es una abreviatura para definir patrones repetitivos en tus columnas o filas sin tener que escribirlos a mano.
/* Sin repeat */ grid-template-columns: 1fr 1fr 1fr 1fr; /* Con repeat */ grid-template-columns: repeat(4, 1fr);¿Cómo uso grid-template-areas?
Te permite "dibujar" literalmente tu layout con nombres en tu CSS. Es excelente para visualizar la estructura del diseño completo a simple vista.
.container {display: grid; grid-template-areas: "header header" "sidebar main" "footer footer";}.header { grid-area: header; }