CSS Introduction | CSS Box Model | Margin
Margin
The margin property sets the size of the margin area, which is the space between the border and neighboring elements.
Unlike the padding area, this margin area is not affected by the background color set with the background-color property.
With CSS, you can set the size of the margin area separately for each direction.
Margin Properties
CSS provides the following properties to set the margin area of an HTML element.
| Property | Description |
|---|---|
| margin | Sets styles using all margin properties in one line. |
| margin-top | Sets the top margin value. |
| margin-right | Sets the right margin value. |
| margin-bottom | Sets the bottom margin value. |
| margin-left | Sets the left margin value. |
You can also set a negative margin value to overlap the element on top of another element.
<style>
div.mar {
margin-top: -25px;
margin-right: 10px;
margin-bottom: 30px;
margin-left: 100px;
}
</style>
If the margin property value is set to inherit, it inherits the margin property value of the parent element.
<style>
div.parent { height: 100px; margin-left: 100px; }
div.child { background-color: #FFF8DC; margin-left: inherit; }
</style>
Margin Shorthand
You can set styles using all margin properties in one line.
<style>
div.four { margin: 20px 50px 30px 50px; }
div.three { margin: 20px 50px 30px; }
</style>
When four margin values are provided, they are set in the order top, right, bottom, left.
Example: margin: 10px 20px 30px 40px;
This has the same meaning as the following four lines.
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
When three margin values are provided, they are set in the order top, right and left, bottom.
Example: margin: 10px 20px 30px;
This has the same meaning as the following four lines.
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 20px;
When two margin values are provided, they are set in the order top and bottom, right and left.
Example: margin: 10px 20px;
This has the same meaning as the following four lines.
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
When one margin value is provided, all margin values are set to the same value.
Example: margin: 10px;
This has the same meaning as the following four lines.
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 10px;
Why Use auto as a margin Value?
When the margin property value is set to auto, the web browser automatically sets the horizontal margin values.
In other words, the left and right margins of the corresponding HTML element are automatically set.
As a result, the element is placed exactly in the center of the parent element that contains it.
<style>
div {
border: 2px solid teal;
width: 300px;
margin: auto;
}
</style>