Learn how to build and design websites with our tutorials.

CSS Margin Tutorial

View Tutorial Contents


The CSS margin property allows you to set the amount of space around HTML elements. This space is between an element and the browser window or other elements. The margin does not have a background color and is transparent.

The Box Model

The image below shows you how the margin, padding, border and the HTML element fit together. This is referred to as the box model.

CSS Box Model


CSS Margin Properties

You can set the top, right, bottom and left margin of an HTML element individually or all at once using either the shorthand margin property or one of the individual margin properties shown below.

The list below shows you the possible margin properties.


CSS Margin Property Values

The possible values of the margin property are listed below.

Value Description
auto The browser calculates the margin
length px, pt, cm, em, etc. (default value is 0px)
% You can set the margin as a percent of the width of the containing element
inherit Specify that the margin inherit the value from the parent element

It is possible to use negative values to overlap content but it is not recommended.


Individual Margin Properties

The CSS example below shows you how to use the individual margin properties to set the margin of an HTML element.


.box{
margin-top:		50px;
margin-right:		40px;
margin-bottom:	30px;
margin-left:		20px;
}


CSS Shorthand margin Property

The CSS margin property allows you to set the margins of an HTML element in one declaration. The margin property can have from one to four values.

The CSS example below shows you how to set all of the margins of an HTML element with only one value.


.box{
margin: 0px;
}

The CSS example below shows you how to set the margins of an HTML element using four values. The first value sets the top margin, the second value sets the right margin, the third value sets the bottom margin and the last value sets the right margin.


.box{
margin: 0px 25px 50px 100px;
}

The CSS example below shows you how to set the margins of an HTML element using three values. The first value sets the top margin, the second value sets the right and left margins and the last value sets the bottom margin.


.box{
margin: 25px 50px 100px;
}

The CSS example below shows you how to set the margins of an HTML element using two values. The first value sets the top and bottom margins and the last value sets the right and left margins.


.box{
margin: 50px 100px;
}