Width and centering
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Width
- By default, a block box is as wide as the page.
width: 300px;makes it a fixed width instead.max-width: 600px;is gentler — at most this wide, but shrink on small screens.
Centering a box
- To center a box (not just its text), give it a width, then
margin: 0 auto;. 0 automeans no top/bottom margin, and equal left/right margins.- Equal side margins push the box into the middle.
<style>
.card {
width: 280px;
margin: 0 auto;
padding: 16px;
background-color: #eef;
}
</style>
<div class="card">A centered card.</div>
Now you try
- A box needs a width before
margin: 0 auto;can center it. - Set a width, then center the card.
Give the card a fixed width. Add width: 300px; to the .card rule.
Center the card on the page. Add margin: 0 auto; to the .card rule.