iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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)

element top right bottom left
Fig 1. margin: 10px 20px 30px 40px goes clockwise from the top.

Shorthand patterns

ShorthandMeans
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 &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Center this block horizontally inside its parent.

.card { width: 320px; margin: 0 ; }

Test yourself

Q1. In the shorthand `margin: 5px 10px 15px 20px`, which side is 15px?
Q2. What does `margin: 0 auto` typically do for a block element?
Q3. Two stacked blocks have `margin-bottom: 20px` and `margin-top: 30px`. The gap between them is…

Discussion

Loading…