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:
What it does
The margin properties set the size of the top, left, bottom, right and all margins respectively.
Margins can be specified as either a percentage, a length or using the keyword auto.
Margins can be negative values.
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
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.
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
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
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.