Labs ICT
โญ Pro Login

Margin

Margins are the personal space of elements. They push other elements away so nothing feels cramped.

Margin Shorthand

You can set margins for all four sides at once using shorthand:

/* All four sides */
.box { margin: 20px; }

/* top/bottom left/right */
.box { margin: 10px 20px; }

/* top right bottom left */
.box { margin: 10px 15px 20px 25px; }
Try it Yourself โ†’

The order in the four-value version is clockwise: top, right, bottom, left. Think of a clock starting at 12.

Individual Properties

If shorthand feels cryptic, you can set each side separately:

.box {
  margin-top: 10px;
  margin-right: 15px;
  margin-bottom: 20px;
  margin-left: 25px;
}

Either way works. The shorthand is just fewer lines to type.

Centering with auto

Want to center a block element horizontally? Set its left and right margins to auto:

.centered {
  width: 300px;
  margin: 0 auto;
}

The browser calculates equal left and right margins automatically. This only works on block elements that have a specified width.

Margin Collapse

Here is a weird thing about CSS: when two vertical margins touch, they combine into one. The resulting margin is the larger of the two.

/* Two boxes stacked vertically */
.box1 { margin-bottom: 30px; }
.box2 { margin-top: 20px; }
/* The gap between them is 30px, not 50px */

This only affects top and bottom margins. Left and right margins always add up normally. Margin collapse surprises everyone at first, but once you know about it, you can plan around it.

๐Ÿงช Quick Quiz

How do you center a block element horizontally?