Westciv Logo

These materials are copyright Western Civilisation Pty Ltd.

www.westciv.com

They are brought to you courtesy of Style Master CSS Editor and Westciv's standards based web development courses.

Please see our website for detailed copyright information or contact us info@westciv.com.

complete css guide

Margin properties

With cascading style sheets, any element can have a margin. A margin is the space between an element and the elements to its top, left, bottom and right. The margin properties are:

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

Browser support

Get browser support information for margin in the downloadable version of this guide or our browser support tables.

What it does

The margin properties set the size of the top, left, bottom, right and all margins respectively.

Possible values

Margins can be specified as either a percentage, a length or using the keyword auto.

Margins can be negative values.

Percentages

A percentage margin value sets the affected margin to that percentage of the width of the parent element. For instance, a margin-right: 20% sets the width of the right margin to 20% of the width of the element which contains the element. Note that this is true even for margin-top and margin-bottom.

Length Values

We cover length values in detail in our section on values. Essentially though there are two types of length value. There are absolute values such as px. If you use one of these, the actual length of the margin will always be the same. You design much more flexible pages if you use a relative value, like em. If you use a relative value the size of the margin will always be proportional to the calculated size of the content of the element. This is to be encouraged.

Default values

If no margin value is specified, the margin of an element is zero. That is, there is no space between an element and adjacent elements. Unfortunately most browsers do tend to set default margins on elements such as paragraphs. You can overcome this by specifically setting the margin for these types of element to 0.

Is it inherited?

An element does not inherit the margin property of the element which contains it.

Hints and suggestions

Margins can be used to achieve similar effects to the positioning properties which we discuss below and padding (we talk about padding next).

You can center an element in its parent, without using text-align on the parent element by giving the element a left-margin and a right-margin of auto.

Using percentage values for your margins is highly recommended for the design of flexible, accessible web pages. A percentage value for a margin ensures that the actual drawn size of the margin will always remain proportional to the size of the viewing portal.

Web Directions Conference
Style Master CSS Editor