CSSintermediate 9 min
Two-dimensional layouts with rows and columns using display grid.
How to lay out items in rows and columns at the same time with CSS Grid, and how to make one item span several cells.
Photo galleries, dashboards and whole page layouts need control in two directions. Flexbox handles one direction at a time. Grid handles both.
Set display: grid on a container and describe its columns with grid-template-columns. The children become grid items placed in the cells.
grid-template-columns: 1fr 1fr 1fr makes three equal columns. fr is a "fraction" of the free space.grid-template-columns: 200px 1fr makes a fixed sidebar and a flexible main area.repeat(3, 1fr) is a shorter way to write three equal columns.gap adds space between rows and columns.grid-column: span 2 makes an item stretch across two columns.repeat(3, 1fr) creates three columns of equal width.grid-column: span 2, so it takes two cells. Row 2 now holds item 4 and item 5.gap: 10px spaces every row and column.Change repeat(3, 1fr) to repeat(4, 1fr), then try 200px 1fr 1fr.
display: grid on the items instead of the container.gap, so items touch.fr and minmax.display: grid plus grid-template-columns builds columns.fr, repeat() and gap keep layouts flexible.grid-column: span n stretches an item.Next: layouts that adapt to every screen size.
<style>
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.grid div {
background: royalblue;
color: white;
padding: 20px;
text-align: center;
border-radius: 8px;
}
.wide {
grid-column: span 2;
background: tomato;
}
</style>
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div class="wide">4 (wide)</div>
<div>5</div>
</div>