Sub topic 2
Margins: the Space Outside the Grid
Assume you know basic HTML, CSS selectors, units, and the box model. A margin is space outside an element’s border. In a page grid, margins keep content away from the viewport edges and help center the layout.
Containers: Maximum Width and Centering
A container is an element that limits the width of page content. Without a maximum width, text lines and grid columns can become too wide on large screens. margin-inline: auto divides leftover horizontal space evenly, which centers the container.
Use padding for the minimum edge space. Padding prevents content from touching the viewport when the container becomes narrow.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.page {
max-width: 72rem;
margin-inline: auto;
padding-inline: 1rem;
}
.grid {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 1.5rem;
}
.main {
grid-column: span 8;
}
.sidebar {
grid-column: span 4;
}
</style>
</head>
<body>
<div class="page">
<div class="grid">
<main class="main">Main content</main>
<aside class="sidebar">Sidebar</aside>
</div>
</div>
</body>
</html>Fixed and Fluid Grids Compared
A fixed grid uses set track sizes, such as 240px. It can provide predictable alignment but may overflow a small viewport. A fluid grid uses flexible units such as fr, which share available space.
| Grid type | Typical track size | Main trade-off |
|---|---|---|
| Fixed | `240px` | Predictable, but can overflow |
| Fluid | `1fr` | Adapts well, but changes width |
Building a 12-Column Grid with CSS Grid
CSS Grid is a layout system that arranges items in rows and columns. repeat(12, 1fr) creates twelve equal flexible columns. The gap property creates gutters. An item can span several columns with grid-column.
Exercise
Why should a wide page use both max-width and margin-inline: auto?
Show answer
max-width prevents the content from becoming too wide, and margin-inline: auto centers the limited-width container.