Learn To Code Now – A book by SuperHi

Margins

Let’s say we want to add a 24 pixel space at the top and bottom of all our paragraphs so our content is easier to read. We want to push other tags away from the tag that’s above and below it:

<p>Going freelance means...</p>

<p>The first step is...</p>

<p>I'm not a fan...</p>

For our users, we want there to be a gap between the first <p> tag and the second <p> tag, then a gap between the second <p> tag and the third <p> tag. If we add a fourth, fifth, sixth or millionth <p> tag later, we want there to be a gap between them by default too.

To get this spacing between each of the tags, we can use the margin rule within CSS. Margins take four values: top, right, bottom, left, clockwise starting from the top. For our paragraphs, we want 24 pixels at the top and 24 pixels at the bottom, but we’re not too fussed about the left or right having a margin so we can make them have zero margin:

p {
    margin: 24px 0 24px 0;
}

We have four values in our margin rule, all separated by spaces. If we decided that, in fact, the design would look better with the left and the right sides to have the same margin as the top and bottom, we’d change our styles to be:

p {
    margin: 24px 24px 24px 24px;
}

If all four sides of the margins are equal, we can add a shortcut in here and just say one value and it’ll apply them to all sides:

p {
    margin: 24px;
}

One thing to remember with margins is that the gap between two tags is an overlap not an addition. For example, if we have two paragraphs, each with 24 pixels margin, the gap between them is 24px, not 48px. However, if we have a header with a 36 pixel margin next to a paragraph with just a 24 pixel margin, the gap between the two tags would be the maximum of the two, so in this case, 36px.

Ask Wilson

Got a question? Ask our smart helper any question and he’ll try to help you out!

Comments

Have your say! Please stick to our community guidelines or your comments will be flagged and removed.

This was a great article, thank you!

Simon the cat