CSS Margins

Margins specify the space and position of the element on the web-page. There are basically 4 properties that can be used to specify the margins for the elements:


  • margin-top
  • margin-bottom
  • margin-right
  • margin-left


The value for the margin properties can be of following 4 types:

  • auto: Auto-Calculated Margins
  • length: Specific length in px, cm, pt etc.
  • percentage: Specific percentage of the containing element
  • inherit: The margin here is inherited from the parent element
  • We will now know more about auto and inherit values.

    auto value

    The auto Value provides the margin so that the element is horizontally centered in its containing element. Here’s an example for the same:


    Here the property being used for margin is the shorthand property for margin.
    Although, the auto Value is only for the horizontal margins, for the rest of the values, the order of margin properties is
    A sample code for the same is:


    inherit value

    As specified earlier, the margin value is inherited from the parent element. For example, if a paragraph or <p> element has its parent element as a <div> then the margin can be inherited as:


    Thus, the <p> element will have a right margin of 100px whenever it is being used within the <div>element.

    Margin collapse

    The margin property has another interesting feature of collapsing into a single margin for the top and bottom values. The following example will help to understand this better:

    Here, the bottom margin for h1 is 40 and the top margin for h2 is 30. Logically, the total margin between h1 and h2 should be 40+30=70px but due to margin collapse, it will be 40px as that is the greater value.