CSS Margin

CSS Margin Properties

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.

Setting Margins for Individual Sides

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:

  • length - sets a margin in px, em, rem, pt, cm, etc.
  • % - sets a margin as a percentage (%) of the width of the containing element.
  • auto - the browser calculates an appropriate margin.
  • inherit - the margin value is inherited from the parent element.

You can also set negative margins on an element, for example, margin: -10px; or margin: -5%;.


The Margin Shorthand Property

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.

  • If one value is given, it applies to all four sides.
  • If two values are given, the first value applies to the top and bottom, and the second value applies to the right and left.
  • If three values are given, the first value applies to the top, the second value applies to the right and left, and the third value applies to the bottom.
  • If four values are given, they apply to the top, right, bottom, and left sides in that order.

Using shorthand properties is recommended because it saves time and makes your CSS code easier to read and maintain.


Horizontal Centering with Auto Margins

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.