Margin is the spacing outside an element.
The margin property specifies the element‘s margins.
A 40-pixel margin added to all sides of an element.
<style>
.margin {
margin: 40px;
padding: 10px;
background: aliceblue;
}
</style>
<div class="margin">
An element with a 40px margin
</div>
This property is a shorthand property for:
The margin values can be any length value, such as, px, %, em, etc.
Margin values can be positive or negative.
margin: length | auto | initial | inherit;
| Value | Description |
|---|---|
| length | Default is 0. Sets a margin using any valid length CSS values. Negative values are allowed. |
| % | Sets margin in percent of the width of the containing element |
| auto | Browser calculates a margin |
| initial | Sets the value to its default value. |
| inherit | Inherits the value from its parent element. |
Click the buttons to see the different margin values.
<style>
.margin-examples {
background: aliceblue;
padding: 10px;
height: 200px;
max-width: 450px;
margin: 5%;
}
</style>
<div class="margin-examples">
margin: 5%
</div>
Click the buttons to see the different margin values.
<style>
.margin-example {
background: aliceblue;
padding: 10px;
max-width: 450px;
margin: 20px 40px 60px 80px;
}
</style>
<div class="margin-example">
margin: 20px 40px 60px 80px
</div>
Single parameter value: all sides of the element use the specified margin value.
Two parameter values: top and bottom, then left and right margins will be set.
Three parameter values: top, left and right, then bottom side.
Four parameter values: top, right, bottom, and left side respectively.
The auto value equalizes left and right margin, placing element in center.
This table shows when margin support started for each browser.
![]() Chrome
|
1.0 | Dec 2008 |
![]() Firefox
|
1.0 | Nov 2004 |
![]() IE/Edge
|
6.0 | Aug 2001 |
![]() Opera
|
3.5 | Nov 1998 |
![]() Safari
|
1.0 | Jun 2003 |