Sub topic 1
Grid Container and Explicit Columns
Prerequisites
You should know basic CSS selectors, the box model, semantic HTML elements such as header and main, and length units such as px, rem, and percentages. This chapter assumes you can read a simple media query.
Creating a Grid Container
A grid container is an element whose direct children are arranged in rows and columns. Set display: grid on the parent. Its children then become grid items.
The following page has two explicit columns. The first is 220 pixels wide. The second uses 1fr, which means one fraction of the remaining space.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.page {
display: grid;
grid-template-columns: 220px 1fr;
gap: 1rem;
}
header, aside, main, footer {
padding: 1rem;
border: 1px solid #999;
}
header { grid-column: 1 / -1; }
footer { grid-column: 1 / -1; }
</style>
</head>
<body>
<div class="page">
<header>Header</header>
<aside>Sidebar</aside>
<main>Main content</main>
<footer>Footer</footer>
</div>
</body>
</html>Sizing Tracks with `fr` and `gap`
A grid track is a row or column. The fr unit distributes available space after fixed sizes and gaps have been deducted. For example, 1fr 2fr gives the second flexible column twice as much remaining space as the first.
The gap property adds consistent space between tracks. It does not create extra space around the outside edge of the grid.
Naming Regions with `grid-template-areas`
Named areas make a page layout easier to read. Each quoted row describes one grid row. Each word names a cell. Repeating a name makes that area span multiple cells.
.page {
display: grid;
grid-template-columns: 220px 1fr;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
gap: 1rem;
}
.page > header { grid-area: header; }
.page > aside { grid-area: sidebar; }
.page > main { grid-area: main; }
.page > footer { grid-area: footer; }Every named area must form a rectangle. Rows must contain the same number of cells. An area cannot appear in disconnected cells or in an L shape.
Exercise
In a 1fr 2fr grid, which column receives more of the remaining space?
Show answer
The second column receives twice as much remaining space as the first.