Boxes in CSS: Margin and padding

Margins

Sometimes you need to have an element keep certain space with the rest of the page. To achieve this, you only need to specify a margin instruction in the CSS file. Specify a global margin or specific margins for each side of the element using the following commands:

margin-top
margin-right
margin-bottom
margin-left
margin

Don't forget that if you use margin as a shorthand instruction, the order goes clockwise from top to left. If you don't specify the four margins, the browser will complete the order for you.

Padding

The padding instruction works just like the margin, except for the fact it lets you specify a margin between the border of an element and its content. It is very useful, too.

padding-top
padding-right
padding-bottom
padding-left
padding

Likewise, if you use the shorthand padding instruction, the order goes clockwise from top to right.

Examples

To specify a right margin of 0.28em to an image, you can do this:

img {
margin-right: 0.28em;
}

or this:

img {
margin: 0 0.28em 0 0;
}

To specify a right and left padding of 0.28em to an image, you can do this:

img {
padding-right: 0.28em;
padding-left: 0.28em
}

or this:

img {
padding: 0 0.28em;
}

In the last case, when the browser reads this last instruction, it will complete it assigning the element a bottom padding of zero and a left padding of 0.28em, just like if you would have written it yourself.

You see? It is very easy.


Knowledge + Computers