CSS · Unit 2: The box model · Lesson 3 of 5
Width, max-width and centering
A block element stretches to fill its container.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
A block element stretches to fill its container. On a wide screen, very long lines of text are tiring to read.
max-width caps the width but still lets the box shrink on small screens. About 60 to 70 characters per line, roughly max-width: 40rem, is comfortable.
margin: 0 auto centers a block that has a width or max-width: the browser shares the leftover space equally between left and right.
Worked example
CSS
.page {
max-width: 40rem;
margin: 0 auto;
padding: 0 16px;
}
The HTML it styles
<main class="page">
<h1>About us</h1>
<p>We repair bikes, fix flats while you wait and teach weekend classes.</p>
</main>
Key terms
- max-width
- A cap on width that still lets the box shrink on small screens.
- Margin
- Space outside the border. margin: 0 auto centers a block with a width.
Practise it in Code Academy
It has 4 exercises (multiple choice, fix the broken code and write code from a prompt) and takes about 6 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.