CSS Margins
- Previous Page CSS Rounded Corners
- Next Page CSS Margin Collapsing
CSS Margins
CSS margin
The property is used to create space around an element outside any defined border.
Through CSS, you can completely control the margins. Some properties can be used to set the margins for each side (top, right, bottom, and left) of an element.
Margin - Individual Side
CSS has properties to specify margins for each side of an element:
margin-top
margin-right
margin-bottom
margin-left
All margin properties can be set to the following values:
- auto - The browser calculates the margin
- length - Specifies the margin in units such as px, pt, cm, etc.
- % - Specifies the margin as a percentage of the width of the containing element
- inherit - Specifies that the margin should be inherited from the parent element
Tip:Negative values are allowed.
Example
Set different margins for all four sides of the <p> element:
p { margin-top: 100px; margin-bottom: 100px; margin-right: 150px; margin-left: 80px; }
Margin - Shorthand Property
To reduce code, you can specify all margin properties in one property.
margin
The property is a shorthand for the following margin properties:
margin-top
margin-right
margin-bottom
margin-left
The working principle is as follows:
If margin
The property has four values:
- margin: 25px 50px 75px 100px;
- The top margin is 25px
- The right margin is 50px
- The bottom margin is 75px
- The left margin is 100px
Example
The margin shorthand property sets four values:
p { margin: 25px 50px 75px 100px; }
If margin
The property sets three values:
- margin: 25px 50px 75px;
- The top margin is 25px
- The right and left margins are 50px
- The bottom margin is 75px
Example
Use a shorthand property that has set three margin values:
p { margin: 25px 50px 75px; }
If margin
The property sets two values:
- margin: 25px 50px;
- The top and bottom margins are 25px
- The right and left margins are 50px
Example
Use a shorthand property that sets two margin values:
p { margin: 25px 50px; }
If margin
The property sets a value:
- margin: 25px;
- All four margins are 25px
Example
Use a shorthand property to set a margin value:
p { margin: 25px; }
auto value
You can set the margin property to auto
, so that the element is horizontally centered in its container.
Then, the element will occupy the specified width, and the remaining space will be evenly distributed between the left and right boundaries.
Example
Using margin: auto
:
div { width: 300px; margin: auto; border: 1px solid red; }
inherit Value
This example makes the left margin of the <p class="ex1"> element inherit from the parent element (<div>):
Example
Using inherit Value:
div { border: 1px solid red; margin-left: 100px; } p.ex1 { margin-left: inherit; }
Further Reading
Supplementary Books:Box Model: CSS Margin
- Previous Page CSS Rounded Corners
- Next Page CSS Margin Collapsing