CSS Grid Basics
CSS Grid is a two-dimensional layout system that lets you control rows and columns simultaneously. You create a grid by applying display: grid to a container, then define its structure.
1. Enabling Grid
Add display: grid to any container to make it a grid container. Its direct children automatically become grid items. Without any other properties, items stack in a single column (same as block layout).
.container {
display: grid;
}
/* children stack in one column by default */2. grid-template-columns
Define how many columns and how wide each column should be. Each space-separated value creates one column track.
.container {
display: grid;
grid-template-columns: 200px 100px 150px;
}3. grid-template-rows
Define row track sizes explicitly. If you have more items than rows, additional rows are created implicitly with auto height.
.container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 80px 40px 60px;
}4. grid Shorthand
The grid shorthand sets both rows and columns together using a slash separator: "rows / columns".
.container {
display: grid;
/* rows / columns */
grid: 60px 80px / 1fr 1fr 1fr;
}
/* equivalent to: */
.container {
grid-template-rows: 60px 80px;
grid-template-columns: 1fr 1fr 1fr;
}5. The auto Keyword
Use auto to let a track size itself based on its content. Auto columns/rows expand to fit their largest item.
.container {
display: grid;
grid-template-columns: auto auto auto;
}
/* each column is as wide as its content */6. Mixing Units
You can freely mix px, %, em, fr, auto and other units in the same track definition.
.container {
display: grid;
grid-template-columns: 100px 1fr 20%;
/* fixed | flexible | percentage */
}