Chapter 20: Margins

The margin is the area on the outside of an element, and thus it is also outside the border of an element.

Example:

<p style="margin: 20px;">text text text text</p>

Output

text text text text

To give each side a different margin:

<p style="margin: 10px 20px 30px 40px;">text text text text</p>

Output

text text text text

This will set the margins in the same order as the padding equivalent. That is top, right, bottom, left. The easiest way to remember this is that it is clockwise starting at the top! You can also set the margins individually like so:

#example
{
 margin-top: 1px;
 margin-right: 2px;
 margin-bottom: 3px;
 margin-left: 4px;
}

The margin of an element is not to be part of the background. And so this area will always be transparent, meaning that anything behind the element (such as the page's background colour) will show through the margin area.

You can also center an element by setting the margin on the left and right hand side to auto.

<p style="width: 100px; background-color: rgb(204,255,153); margin-left: auto; margin-right: auto;">test test</p>

Output

test test

Setting the margin to auto on both sides forces the margin on each side to take up as much space as possible in the container element, thus centering the element. This is a fairly unknown CSS gem. Please note that Microsoft Internet Explorer needs a little help to get this to work. This will be covered in a later chapter.

Have a quick go yourself, and then take the quiz!