The CSS way to style margins and padding

Instead of using lines of paragraphs or lots of breaks, to create more space, just manipulate an object's margins and padding.

A question that gets asked a lot is: what's the difference between margins and padding? Well, padding is added inside an element. Margins are applied to the outsides of an element. Note that padding contributes to an element's width and height, whereas margins do not.

Examples

Overall

margin:6px; padding:6px;

This will set all margins and all padding to 6px.

Various sides

If we want to manipulate the margins and padding of various sides of an element, we would do the following.

margin:top right bottom left;

The shorthand properties for margins are applied in a clockwise direction, starting at the top and then going to the right, bottom and left.

margin:0 5px 0 10px;

This example applies a right margin of 5px and a left margin of 10px.

margin:0 5px 0 10px

The advantages of using shorthand are that it saves time and also bandwidth. You don't necessarily need four distinct values though. You can use it with just three:

margin:10px 25px 4px 10px;

Top and left margins are set to 10px, the right is set to 25px and the bottom is set to 4px.

margin:10px 25px 4px 10px

Or, as in our first example, two distinct values:

padding:0 5px;

Top and bottom have a padding of 0 and left and right have a padding of 5px.

padding:0 5px

Or one distinct value:

margin:0;

All margins are set to zero.

Margins and padding can also be written out in their full form:

margin-right:4px; padding-bottom:15px;

Here, we're setting a right margin of 4px and a padding bottom of 15px.

Got any questions or comments? Feel free to mail me @ helen@alternategateways.com.

Back to resources.