Javatpoint Logo

91-9990449935

 0120-4256464

CSS Margin

CSS Margin property is used to define the space around elements. It is completely transparent and doesn't have any background color. It clears an area around the element.

Top, bottom, left and right margin can be changed independently using separate properties. You can also change all properties at once by using shorthand margin property.

There are following CSS margin properties:

CSS Margin Properties

Property Description
margin This property is used to set all the properties in one declaration.
margin-left it is used to set left margin of an element.
margin-right It is used to set right margin of an element.
margin-top It is used to set top margin of an element.
margin-bottom It is used to set bottom margin of an element.

CSS Margin Values

These are some possible values for margin property.

Value Description
auto This is used to let the browser calculate a margin.
length It is used to specify a margin pt, px, cm, etc. its default value is 0px.
% It is used to define a margin in percent of the width of containing element.
inherit It is used to inherit margin from parent element.

Note: You can also use negative values to overlap content.


CSS margin Example

You can define different margin for different sides for an element.

Test it Now

Output:

This paragraph is not displayed with specified margin.

This paragraph is displayed with specified margin.


Margin: Shorthand Property

CSS shorthand property is used to shorten the code. It specifies all the margin properties in one property.

There are four types to specify the margin property. You can use one of them.

  1. margin: 50px 100px 150px 200px;
  2. margin: 50px 100px 150px;
  3. margin: 50px 100px;
  4. margin 50px;

1) margin: 50px 100px 150px 200px;

It identifies that:

top margin value is 50px

right margin value is 100px

bottom margin value is 150px

left margin value is 200px

Test it Now

Output:

This paragraph is not displayed with specified margin.

This paragraph is displayed with specified margin.


2) margin: 50px 100px 150px;

It identifies that:

top margin value is 50px

left and right margin values are 100px

bottom margin value is 150px

Test it Now

Output:

This paragraph is not displayed with specified margin.

This paragraph is displayed with specified margin.


3) margin: 50px 100px;

It identifies that:

top and bottom margin values are 50px

left and right margin values are 100px

Test it Now

Output:

This paragraph is not displayed with specified margin.

This paragraph is displayed with specified margin.


4) margin: 50px;

It identifies that:

top right bottom and left margin values are 50px

Test it Now

Output:

This paragraph is not displayed with specified margin.

This paragraph is displayed with specified margin.

Next TopicCSS Opacity