The CSS margin properties let you set the space around the edge of an element's box, including its border if it has one.
An element's margin is always transparent and isn't affected by its background-color
. However, if the parent element has a background color, it will show through the margin area.
You can set the margins for the top, right, bottom, and left sides of an element individually using the CSS margin-top
, margin-right
, margin-bottom
, and margin-left
properties. Let's check out an example to see how it works:
h1 {
margin-top: 50px;
margin-bottom: 100px;
}
p {
margin-left: 75px;
margin-right: 75px;
}
Margin properties can be defined using these values:
You can also set negative margins on an element, for example, margin: -10px;
or margin: -5%;
.
The margin
property is a shorthand method to set margins for all sides at once, instead of setting margin-top
, margin-right
, margin-bottom
, and margin-left
separately.
Here’s an example to show how the shorthand property works:
h1 {
margin: 50px; /* apply to all four sides */
}
p {
margin: 25px 75px; /* vertical | horizontal */
}
div {
margin: 25px 50px 75px; /* top | horizontal | bottom */
}
hr {
margin: 25px 50px 75px 100px; /* top | right | bottom | left */
}
This shorthand notation can take one, two, three, or four space-separated values.
Using shorthand properties is recommended because it saves time and makes your CSS code easier to read and maintain.
The auto
value for the margin property lets the browser automatically calculate the margin. This is often used to center an element horizontally within a larger container.
Let’s try an example to see how it works:
div {
width: 300px;
background: gray;
margin: 0 auto;
}
The above style rules make the <div>
element take up 300 pixels of the horizontal space, and the remaining space will be equally divided between the left and right margins.