CSS margin property syntax and examples

CSS margin property the values of the outer edge of an element. The margin-top, margin-right, margin-bottom, and margin-left properties are used to set the margins separately.


css margin property


The margin property can be applied to all elements except the elements of the table type.


margin: length|auto|initial|inherit;

The CSS margin property takes the following values.

  • auto: It is automatically calculated by the browser.
  • length: Specifies a margin in cm, em, px etc.
  • %: Calculates the margin property as a percentage by container element.
  • inherit: This property inherits from a parent element. Read more inherit

The initial value of the CSS margin property is zero. Also, this feature can not be inherited.

CSS margin examples:

The CSS margin property has multiple uses. Below you can see examples of this.

/* Sets all margins to 30 pixels. */
margin: 30px;

/* top | right | bottom | left (clockwise) */
margin: 10px 15px 20px 30px;

/* vertical | horizontal */
margin: 20px auto;

/* top | horizontal | bottom */
margin: 2em auto 1%;
  • The first example applies to all four sides.
  • The second example allows the values of each corner to be given separately.
  • The third example allows you to set the margin property of the element horizontally and vertically.
  • In the fourth example, the margin property has 3 values; the first value is the top, the second value is horizontal, and the third value is bottom.

Margin – Individual Sides

The CSS margin property allows you to set the value of each edge individually.

margin-top Sets the margin property from the top according to the container element.
margin-right  Sets the margin property on the right according to the container element.
margin-bottom  Sets the margin property on the bottom according to the container element.
margin-left  Sets the margin property on the left according to the container element.


p {
/* sets different margins for all four sides */
margin-top: 1em;
margin-right: 5%;
margin-bottom: -25px;
margin-left: auto;