HTML & CSS · Beginner · 15 min
Control spacing with the box model
Distinguish content, padding, border, and margin.
Inside and outside spacing
Padding creates space between content and border. Margin creates space outside the border. A background covers content and padding. Keeping these roles separate helps you adjust a card without adding empty paragraphs or repeated spaces.
<style>
.card { padding: 16px; margin: 8px; border: 2px solid navy; }
</style>
<article class="card">A learning card</article>Expected appearance
padding: 16px margin: 8px border-width: 2px
Include padding in the width
With content-box, a declared width excludes padding and borders. With border-box, it includes them. A max-width prevents a card from growing too wide; width: 100% lets it fit a smaller container. Margin is outside the box in both models.
<style>
.card { box-sizing: border-box; width: 100%; max-width: 320px; padding: 16px; border: 2px solid navy; }
</style>
<article class="card">A learning card</article>Expected appearance
box-sizing: border-box max-width: 320px
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Edit the page content and include CSS in a style element. The preview supports a limited set of HTML elements. Scripts, external resources, navigation to other sites, and form submission are disabled.
Build and check
Style the article.card with box-sizing: border-box, padding: 16px, a 2px solid navy border, width: 100%, and max-width: 320px.
Use one .card rule. Set width and max-width together so the card can shrink.
Show worked solution
<style>
.card { box-sizing: border-box; padding: 16px; border: 2px solid navy; width: 100%; max-width: 320px; }
</style>
<article class="card">A learning card</article>Use one .card rule. Set width and max-width together so the card can shrink.
Page preview
Run to preview your page. Check tests the task requirements, including the requested screen widths. Check results do not replace keyboard and visual review.
Try it yourself
- Change padding and margin separately and observe what moves.
- Preview the card at a narrow width and check that it fits.