Spacing between elements

Where are we?

You make layouts by creating regions. Regions are visual chunks:

Regions example

Figure 1. Regions

One thing you need to do is set the spacing around regions. This lesson shows you how.

This lesson’s goals

By the end of the lesson, you should:

  • Know what the box model is, and how to use it.
  • Know how to set margin and padding defaults.
  • Know how CSS overrides work.
  • Know how containership affects layout.

The box model

Browsers draw HTML block elements, like <p>, <div>, and <h1>, in boxes. The boxes might not be visible, but they are still there.

The “box model” shows how boxes work. Here’s an example we looked at earlier.

Box model

Figure 2. The box model

Here’s how I created this box:

.big_margin_padding {
  margin: 20px;
  padding: 20px;
  border: dotted 2px #668014;
}
...
<img class="big_margin_padding" ...>

Figure 3. CSS for the dog box

padding is the gap between the content (an <img> tag in this case) and the border. margin is the gap between the border and the box’s edge.

This:

margin: 20px;

sets the same margin on all sides of the element: top, right, bottom, and left.

You can set the values individually for margin and padding, like this:

.different_margins {
  margin-top: 20px;
  margin-right: 10px;
  margin-bottom: 0;
  margin-left: 5px;
}

Figure 4. Separate values

If a gap is zero (like margin-bottom above), you don’t need to add the px.

You can put the values on one line, like this:

.different_margins {
  margin: 20px 10px 0 5px;
}

Figure 5. Separate values on one line

How to remember which number is which? The first number is for the top, and then go clockwise from there:

Which margin is which

Figure 6. Which margin is which

This works for both margin and padding.

Exercise: Dog spacing

Here’s an image:

A dog

Figure 1. A dog

Write a page that looks like this:

Dog spacing

Figure 2. Dog spacing

The margins are all 10px. The padding is 10px on each side, except for the bottom, where it’s 30px. The border is 2px wide, dotted, with a color code of #BBBBBB.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Margin and padding defaults

Browsers have defaults for margin and padding. So if you don’t specify margin and padding, the browser adds them for you.

Usually this works just fine. But when you do page layouts, the defaults can be a problem. Different browsers use different defaults, so a layout that works in one browser can look strange in another.

Webers often add “reset styles” to deal with the problem. For example, you might find this at the top of a page:

* {
  margin: 0;
  padding: 0;
}

Figure 7. A reset rule

The * is the CSS universal selector. It selects every type of tag on the page. This rule gives every element no padding and no margin.

If you do this, you might add margin and padding back to some elements, creating your own defaults for the page. For example:

* {
  margin: 0;
  padding: 0;
}
p {
  margin: 10px 0 10px 0;
}
img {
  margin: 10px;
  padding: 10px;
}

Figure 8. Reset and set known defaults

Every <p> and <img> on the page will use these values. Unless you add other rules.

Overriding

The defaults apply unless you override them for specific elements. Suppose I had this code.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>CSS Override</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      body {
        font-family: "Trebuchet MS", sans-serif;
        font-size: 14px;
      }
      img {
        margin: 20px;
        padding: 5px;
        border: 2px dotted #008000;
      }
      #beet {
        background-color: #B2C3CF;
        margin: 5px;
        padding: 5px;
        border: 3px black double;
      }
    </style>
  </head>
  <body>
    <h1>CSS Override</h1>
    <p><img id="bear" src="bear.png" alt="Bear"></p>
    <p><img id="beet" src="beet.png" alt="Beet"></p>
  </body>
</html>

Figure 9. Overrides

There are five elements on the page: an <h1>, two <p>s, and two <img>. The browser applies styles to each one, based on the CSS.

Have a look at beet, the second image in line 31. What style rules apply to it? These rules:

  • Lines 7-9: This rule applies to everything, so it applies to beet.
  • Lines 11-14: This rule applies to everything in the <body>, so it applies to beet.
  • Lines 15-19: This rule applies to all <img>s. beet is an <img>, so the rule applies to beet.
  • Lines 20-25: This rule applies to everything with an id of beet. So, of course, it applies to beet.

So all of these rules apply. But the rules conflict. For example:

  • Line 8: margin: 0;
  • Line 16: margin: 20px;
  • Line 22: margin: 5px;

What does the browser do? The answer: it applies the most specific rule. The most specific rule is the one that applies just to beet (lines 20 to 25). The next most specific rule is the one that applies to all <img>s (lines 15 to 19). The least specific rule is the one that applies to all elements on the page (lines 7 to 9).

So we would expect the browser to use line 22, and give beet a margin of 5px. Here is what the browser shows:

Overriding margin

Figure 10. Overriding margin

You can see that the gap from the left of the screen to the beet (5px, from line 22) is smaller than the gap from the left to the bear (20px, from line 16). This is what we expect.

You can try the page.

Renata
Renata

In the CSS code, the rule for beet comes after the others. Does that make a difference to what rule the browser uses?

Kieran
Kieran

No, it doesn’t make a difference. Move the #beet {} rule to the top, and it would look the same. It’s the specificity that matters.

Exercise: Spacing for dead dudes

Here are some dead dudes:

Ferdinand de Soto

Ferdinand Magellan

Francisco Pizarro

Create a page that looks like this:

Spacing for dead dudes

Figure 1. Spacing for dead dudes

The spacing around the images is 5px, except for the middle one. That’s 20px.

Use exactly this HTML:

<p>
  <img src="Ferdinand_de_Soto.png" alt="Ferdinand de Soto"><br>
  Ferdinand de Soto
</p>
<p id="magellan">
  <img src="Ferdinand_Magellan.png" alt="Ferdinand Magellan"><br>
  Ferdinand Magellan
</p>
<p>
  <img src="Francisco_Pizarro.png" alt="Francisco Pizarro"><br>
  Francisco Pizarro
</p>

Figure 2. Dead dude HTML

Use CSS overriding to redefine Magellan’s look.

Hint: Mess with the styles for <p> tags in this exercise, not the styles for the <img> tags.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Containers

An important part of layout is knowing how to nest elements. You’ve already seen this in lots of examples, though you might not have noticed. But when laying out pages, you have to pay attention to nesting.

Each element is inside a container. The outer visible container is the <body> element. Everything is inside that. In your HTML, elements are inside <div>s, <p>s, <blockquote>s, and other tags.

Here’s a line from Figure 9.

<p><img id="bear" src="bear.png" alt="Bear"></p>

The <img> is contained in the <p>.

CC
CC

What about headings? Like this:

<h1>Sheltie Habits</h1>
<p>Shelties bark a lot. A <em>lot</em>.</p>

You get:

Headings

The text “Shelties bark a lot” looks like it’s contained in the section “Sheltie Habits.”

Kieran
Kieran

Good question.

The word “contained” has more than one meaning. I’m talking about structural containership. You get structural containership when HTML tags are nested inside each other.

In this code:

<h1>Sheltie Habits</h1>
<p>Shelties bark a lot. A <em>lot</em>.</p>

the <p> tag is not structurally contained in the <h1>.

CC
CC

Oh, I see. But the <em> is contained in the <p>, right?

Kieran
Kieran

Yes! The start and end of the <em> tag are both inside the <p> tag.

CC
CC

But as far as the meaning of the page goes…

Kieran
Kieran

Right! The look of the page, with the heading being in a large font, makes it clear to users that the concept in “Shelties bark a lot” belongs to the topic “Sheltie Habits.”

Renata
Renata

Because that’s what we’re used to seeing.

Kieran
Kieran

Yes, exactly. Newspapers, books, use this convention. Big text for headlines and section headings, smaller text for stuff that belongs under those headings.

But this is just a convention we’ve gotten used to. A shared habit, if you like. There’s nothing in the HTML that says that the <p> is part of the <h1>.

When a tag is contained in another, the outer tag is drawn first, and then the inner tag is drawn inside it. This means that the margins and padding applied to the outer tag move the entire inner tag around.

Let’s say we had this:

<div id="outer">
  <p id="walrus">Walrus</p>
  <div id="inner1">
    <p id="hippo">Hippo</p>
  </div>
  <div id="inner2">
    <p id="dog">Dog</p>
  </div>
  <div id="inner3">
    <p id="cat">Cat</p>
    <div id="inner3_inner">
      <p id="bird">Bird</p>
    </div>
  </div>
</div>

Figure 11. HTML containers

Everything is inside outer. Some things are nested deeply. bird is inside inner3_inner is inside inner3 is inside outer.

Here’s some CSS to go along with Figure 11.

* {
  margin: 0;
  padding: 0;
}
#outer {
  margin: 10px;
  padding: 12px;
  border: 2px dotted #B7B2CF;
}
#inner1 {
  background-color: #B2C3CF;
  margin: 20px;
  padding: 30px;
  border: 1px solid black;
}
#inner2 {
  margin: 20px;
  padding: 10px;
}
#inner3 {
  margin: 5px;
  padding: 10px;
  border: 2px #008000 dashed;
}
#inner3_inner {
  margin: 10px;
  padding: 8px;
  border: solid blue 1px;
  background-color: #CFC9B2;
}

Figure 12. CSS for the HTML containers

Here’s what you get:

Result

Figure 13. Result

The position of an element depends on its margins and padding, and the margins and padding of its containers.

Containers are also called parents. So inner3_inner is a parent of bird.

The browser gets this (line 12 of Figure 11):

<p id="bird">Bird</p>

It shows the text “Bird,” somewhere on its window. Let’s see if we can figure out how far the text “Bird” should be from the left edge of the browser’s window.

bird is inside inner3_inner. inner3_inner has a margin of 10 pixels, padding of 8, and a 1 pixel border. That’s 10 + 8 + 1 = 19 pixels so far.

inner3_inner is inside inner3. inner3 has a margin of 5 pixels, padding of 10, and a 2 pixel border. That’s 5 + 10 + 2, plus the 19 pixels we had earlier. That’s 36 pixels.

inner3 is inside outer. outer has a margin of 10 pixels, padding of 12, and a 2 pixel border. That’s 36 (from before) + 10 + 12 + 2 = 60 pixels.

So the text “Bird” should be 60 pixels from the left of the document.

Renata
Renata

The text “Bird” is inside a <p> tag:

<p id="bird">Bird</p>

Wouldn’t that add some spacing to the left?

CC
CC

Oo, oo! Can I answer?

Kieran
Kieran

OK.

CC
CC

There’s a reset:

* {
   margin: 0;
   padding: 0;
}

So the <p> has no margin or padding.

Kieran
Kieran

That’s right!

So we’ve worked out that the text “Bird” should be 60 pixels from the left. How do we tell what actually happens?

I add some JavaScript to the page. Try it. Move the mouse over each text element, and you’ll see the left and top position of each one. “Bird” is where we thought it should be. W00f!

Exercise: Where are the animals?

Go through the CSS on the animal names page. Work out what you think the top and left position of each animal name should be (for walrus, hippo, etc.). Then compare it with what the page actually does.

Below, type in the positions you worked out, and what the page actually does.

(Log in to enter your solution to this exercise.)

Summary

In this lesson, you learned:

  • What the box model is, and how to use it.
  • How to set margin and padding defaults.
  • How CSS overrides work.
  • How containership affects layout.

What now?

Now you know how to add space around elements. You can use margin and padding with page regions (like top, left, right, etc.).

Now let’s see how to move regions to the left and right.


How to...

Lessons

User login

Log in problems? Try here


Dogs