JavaScript Tutorial

CSS Margin

This 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.

We can have top, bottom, left and right margin which can be changed independently using separate properties. We can also change all properties at once by using shorthand margin property.

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.

There are different type of margin values supported:-

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 the margin from the parent element.

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

Input:-

 

Output:-

The Margin Shorthand Property

The margin property is a shorthand property to avoid setting padding of each side separately, i.e., margin-top, margin-right, margin-bottom and margin-left.

The below example illustrates the use of margin properties with single property use.

Input:-

 

Output:-

Horizontal Centering with Auto Margins

The auto value for the margin property tells the web browser to automatically calculate the margin. This is commonly used to center an element horizontally within a larger container.

Input:-

 

Output:-

The above style rules let the <div> element take up 200 pixels of all the horizontal space available, and the remaining space will be equally divided between left and right margins.

Go back to Previous Course