The Box Model›Core· 35 min read
Margins & Padding
Control the spacing inside and around every element — the bread and butter of good layout.
What you will learn
- Set padding and margin on each side
- Use shorthand for all four sides
- Centre a block with margin auto
Each side, or all at once
You can set each side (margin-top, padding-left...) or use the shorthand:
| Shorthand | Means |
|---|---|
margin: 20px; | All four sides 20px |
margin: 10px 20px; | top/bottom 10, left/right 20 |
margin: 5px 10px 15px 20px; | top, right, bottom, left (clockwise) |
<style>
.a { padding: 20px; background: #e0e7ff; margin-bottom: 12px; }
.b { padding: 10px 30px; background: #c7d2fe; margin-bottom: 12px; }
.center { width: 200px; margin: 0 auto; background: #4338ca; color:#fff; padding: 12px; text-align:center; }
</style>
<div class="a">padding: 20px all sides</div>
<div class="b">padding: 10px top/bottom, 30px left/right</div>
<div class="center">margin: 0 auto centres me</div>Live preview
Three boxes, three lessons in spacing:
.ausespadding: 20px— one value means all four sides get 20px of inner space..busespadding: 10px 30px— two values mean top/bottom = 10px and left/right = 30px, so it is taller-feeling and wider-padded..centerusesmargin: 0 auto— the0is top/bottom margin andautotells the browser to split the leftover left/right space equally, which centres the box. It only works because the box has a fixedwidth: 200px.
Tip: margin: 0 auto; is the classic way to centre a block element horizontally — the left and right margins split the leftover space equally. The element needs a width for this to work.
Note: Top and bottom margins between two block elements collapse — they merge into the larger of the two, rather than adding up. This surprises beginners; it is normal CSS behaviour.
Q. How do you horizontally centre a block element with a set width?
Answer: margin: 0 auto splits the leftover horizontal space equally on both sides, centring the block (it needs a width).
✍️ Practice
- Centre a 300px-wide card on the page using
margin: 0 auto. - Use shorthand to set different padding on each side of a box.
🏠 Homework
- Add comfortable padding and spacing to every section of your profile page.