CSS Grid, explained by touching the grid
Change the number of columns, the gap and the alignment, make a cell span 2×2 and watch the CSS it generates.
CSS Grid lab
Grid creates a grid of rows and columns and places elements into the cells. Unlike Flexbox, it controls both dimensions at once.
Generated CSS
fr, repeat() and minmax()
The fr unit ("fraction") shares out the free space. repeat() saves you repeating by hand.
.rejilla {
display: grid;
/* 3 columnas iguales */
grid-template-columns: repeat(3, 1fr);
/* barra lateral fija + contenido flexible */
grid-template-columns: 250px 1fr;
/* columnas que se adaptan solas: tantas de min. 200px como quepan */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}
repeat(auto-fit, minmax(200px, 1fr)) is the recipe for a responsive card gallery with no media queries.Making a cell span several
On each child you can say how many columns or rows it spans:
.destacada {
grid-column: span 2; /* ocupa 2 columnas */
grid-row: span 2; /* y 2 filas */
}
/* o posición exacta por líneas de la rejilla */
.cabecera {
grid-column: 1 / -1; /* de la primera línea a la última: todo el ancho */
}
Grid vs Flexbox
| Flexbox | Grid | |
|---|---|---|
| Dimensions | one (row or column) | two (rows and columns) |
| Ideal for | bars, button rows, aligning things | page layout, galleries, dashboards |
| Starting point | the content leads | the grid leads |
They do not compete: they are used together. Grid for the overall structure, Flexbox inside each cell.