6.7 CSS margin

To push away your neighbours

If padding adds space inside an element (between its border and its content), margins adds space outside between an element and other elements.

<p>Hey, you know what sucks?</p>
<p>vaccuums</p>
<p>Hey, you know what sucks in a metaphorical sense?</p>
<p>black holes</p>
<p>Hey, you know what just isn't cool?</p>
<p>lava?</p>

Hey, you know what sucks?

vaccuums

Hey, you know what sucks in a metaphorical sense?

black holes

Hey, you know what just isn't cool?

lava?

p{ margin: 40px;}

Hey, you know what sucks?

vaccuums

Hey, you know what sucks in a metaphorical sense?

black holes

Hey, you know what just isn't cool?

lava?

Merging vertical margins

Let’s have a title and a subtitle.

.title{ margin-bottom: 30px;}
.subtitle{ margin-top: 15px;}
<h1 class="title">MarkSheet</h1>
<h2 class="subtitle">A simple HTML/CSS tutorial</h2>

MarkSheet

A simple HTML/CSS tutorial

As the title of this section may have hinted at the answer, the margin between the two elements will be 30px, and not 45px. That is because margins that “touch” each other will merge with each other.

“That’s weird!”

You can consider an element’s margin as the minimum space it want to stay away from other elements.

It’s like the element saying: “Ok, I want the next element to be at least 30px away from me. If it’s more, why not. But at least 30px please!”

Choosing between margin and padding

Tricky question. This question comes up when no border nor background is applied. Indeed: if a border or a background is set on either element, the visual rendering will be different. But if none is present, and considering margins and paddings are transparent, the result will look the same.

Ask yourself why you’re spacing things. Is it to allow the inner content to breath more? Or is to allow the whole element to breath more? It’s padding in the first case, margin in the second.

Also, considering how margins can merge.

Back to top

Learn CSS with my ebook

This ebook is a step by step guide in which I teach you how to build your own personal webpage from scratch, line by line, with HTML5, CSS3, and even JS.

CSS in 44 minutes book cover
Get it now
Close