CSS Margins
The margin property sets the space outside an element's border — the gap between this box and its neighbours.
Shorthand order: TRBL (top, right, bottom, left)
margin: 10px 20px 30px 40px goes clockwise from the top.Shorthand patterns
| Shorthand | Means |
|---|---|
margin: 10px; | All four sides 10px. |
margin: 10px 20px; | Top & bottom 10px, left & right 20px. |
margin: 10px 20px 30px; | Top 10, right & left 20, bottom 30. |
margin: 10px 20px 30px 40px; | Top, right, bottom, left. |
margin: 0 auto; | Centre a block element horizontally. |
Note: Vertical margins between block elements collapse. Two stacked blocks with
margin-bottom: 20px and margin-top: 30px end up 30px apart — not 50.Tip: For consistent layouts, set margins on one side only (e.g. always
margin-top). It side-steps most collapsing surprises.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Margins</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Center this block horizontally inside its parent.
.card { width: 320px; margin: 0
; }
A keyword that asks the browser to share leftover space equally.
Discussion
Loading…