Little Web Hut

CSS 2.1 Reference: margin Property

CSS margin Property
Syntax
selector {margin: width width width width;}
  • A minimum of 1 and a maximum of 4 width values may be specified.
  • width is specified by using a length, percentage, or the keyword auto.
(OR)
selector {margin: value;}
  • value is specified by using the keyword inherit.
Usage

The margin property is used as a shorthand method to specify all 4 margin widths in one place. See the Box Model for a description of the boxes that are generated for elements and the relative position of the margins.

If a percentage value is used, the value will be a percentage of the containing block's width.

  • The Individual margin sides are specified as follows:
    • If 1 width is specified - All 4 margins are set to this width.
    • If 2 widths are specified - 1st width = top and bottom margins, 2nd width = left and right margins.
    • If 3 widths are specified - 1st width = top margin, 2nd width = left and right margins, 3rd width = bottom margin.
    • If 4 widths are specified - 1st width = top margin, 2nd width = right margin, 3rd width = bottom margin, and 4th width = left margin.

CSS Example: The margin property is set using a single value.
  #tst1 {margin: 3em;}
Test It HTML StyleTest It XHTML StyleTest It HTML5 Style

CSS Example: The margin property is set using 2 values.
  #tst1 {margin: 3em 10px;}
Test It HTML StyleTest It XHTML StyleTest It HTML5 Style

CSS Example: The margin property is set using 3 values.
  #tst1 {margin: 3em 10px 6em;}
Test It HTML StyleTest It XHTML StyleTest It HTML5 Style

CSS Example: The margin property is set using 4 values.
  #tst1 {margin: 3em 20px 30px 50%;}
Test It HTML StyleTest It XHTML StyleTest It HTML5 Style

Keywords
  • auto - The margin width is automatically determined by the browser.
  • inherit - A single inherit keyword is used to specify that the values for this property should be taken from the parent element. If inherit is used with the root element, then the initial values for this property will be used. When the inherit keyword is used, no other property values are allowed.
Applies To All elements except elements with the following display types: table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell.
Inherited No
Initial Value 0 for each of the four individual margin sides.


margin Property Examples
Test It HTML StyleTest It HTML StyleTest It HTML5 StyleThe margin property is set using a single value.
Test It HTML StyleTest It HTML StyleTest It HTML5 StyleThe margin property is set using 2 values.
Test It HTML StyleTest It HTML StyleTest It HTML5 StyleThe margin property is set using 3 values.
Test It HTML StyleTest It HTML StyleTest It HTML5 StyleThe margin property is set using 4 values.