Sub topic 1
CSS Grid: Creating a Grid Container
Prerequisites
You should know basic HTML structure, CSS selectors, the box model, normal document flow, and length units such as px, %, and rem.
Creating a grid container
CSS Grid is a layout system for placing elements in rows and columns. An element becomes a grid container when its display property is set to grid. Its direct children become grid items.
<!doctype html>
<html lang="en">
<head>
<style>
.container {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: auto auto;
gap: 16px;
}
.container > div {
padding: 1rem;
background: lightblue;
}
</style>
</head>
<body>
<section class="container">
<div>Sidebar</div>
<div>Main content</div>
<div>Extra content</div>
</section>
</body>
</html>Defining columns and rows
grid-template-columns defines column tracks. A track is a row or column in the grid. grid-template-rows defines row tracks.
The example creates three columns. The first is 200 pixels wide. The other two use flexible space. The two auto values create rows sized according to their content.
Flexible tracks with the fr unit
fr means fraction of the available space. After fixed sizes and gaps are accounted for, remaining space is divided among flexible tracks. Two 1fr columns therefore receive equal widths.
Repeating tracks with repeat()
The repeat() function avoids writing the same track size multiple times.
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1rem;
}This creates four equal columns. Use repeat() when a grid has several tracks with the same sizing rule.
Spacing tracks with gap
gap adds space between rows and columns. It does not add space around the outside edge of the container. You can use one value for both directions or separate values:
.grid {
row-gap: 1rem;
column-gap: 2rem;
}Exercise
A container has three equal columns and a 24px space between every row and column. Which declaration creates it?
Show answer
display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px;