Nothing is for sale here. Freewill tips keep the site running. Want to help? → Tip via Paypal

Margins

Adding a margin of empty space around an HTML element is easy:

div {margin: 20px;}

If that were in an external or embedded style sheet, wherever a division tag was used there would be 20 pixels of empty space around the division area.

If I lived \in caveman times, instead of carrying a big club I would carry a small twig. That way, when a wise-guy cavemen said "look, he's only got a small twig," and all the other cavemen started laughing at me, I could say "Sure, it’s a small twig, but it’s the Twig of Bright Ideas."

They would surely all feel stupid because they made fun of the Twig of Bright Ideas. Then I could hit them up for a free beer. Cavemen are suckers for that trick.

In the true story to the left, shock emoji you can see how a margin of 40 pixels on the right created the space around the division element.

As with the padding and border properties of the box model:

  ► Each margin can be the same, or
  ► the top and bottom and the sides can be different from each other, or
  ► all four sides can have a different value.

To set each margarine … uh, I mean, to set each margin the same:

div {margin: 23px}

With that in your style sheet all divisions would have a margin of 23 pixels on each side.

To set each margin to a different size:

div {margin-top: 15px;
      margin-right: 30px;
      margin-bottom: 10px;
      margin-left: 20px;}

To set the individual margins using the shortcut method, just work clockwise from the top. The shortcut code in the following example means the same as the above long version.

div {margin: 15px 30px 10px 20px;}

Obviously the shortcut method is less coding. You just have to remember the correct order, which is clockwise starting from the top. Got it? Great, you’re a quick study!

Finally, if your want the top and bottom margins the same, and you want the side margins the same but different from the top and bottom, here’s the shortcut for that:

div {margin: 20px 8px;}

With that shortcut method the first number is the top and bottom and the second number is both sides. So in that example, there would be a 20 pixel margin at the top and bottom of the division, and an 8 pixel margin on the sides.

And that’s how we spread the margarine. Wait . . . did I already do the margarine gag? Pretend you didn’t see it the second time, okay? rolling eyes emoji