The CSS Margin Attribute
This is a shorthand property for assigning the width of all the margins of an HTML element. Use the syntax margin:value. The syntax margin-?:value where ? is one of left, right, top or bottom is used to set individual margins. The width can be specified in any legal units of measurement as discussed here. We recommend the use of em units. Negative values can be used to deliver overlap effects which would otherwise be difficult to achieve. The bottom and top margins of successive block elements are collapsed. We have discussed this at length elsewhere. The left and right margins of successive inline elements do not collapse, nor do any of the margins of floated elements. An understanding of the CSS Box Model is vital for the proper utilization of the margin attribute.
By default, elements do not have margins. The exception is the body element which does have a non-zero margin. The precise value is browser dependant. In the interests of consistency it is best assign a value to this attribute for the body element.
Left and right margins can be assigned the value auto rather than a numeric value. This causes block elements to be horizontally centred inside their parent element. Naturally, this will only deliver a visible effect if the block element has a width attribute setting - failing which it would occupy the clientwidth of its parent. IE6 understands the auto setting only when the strict HTML DTD is used.
Browsers are very bad at correctly interpreting shorthand assignments for this attribute. Only the following combinations work across all three browsers discussed on this site:
margin:value;- Assigns a margin width of value to all the margins of the element.margin:value auto;- Assigns a margin width of value to the top and bottom margins and centers the element horizontally in its parent.margin:valueone auto valuetwo;- Assigns a top margin of valueone and a bottom margin of valuetwo. The element is horizontally centered in its parent.
This is not an inherited property - i.e. in a child element, if not assigned, it takes the default value rather than the corresponding value in its parent container.
This attribute can also be assigned the setting inherit which causes it to pick up its value from the parent element.