Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Margins – CSS

Demo

The background color and borders have been changed in the demo to make the margins clearer.

Summary

To change the margins of an element using CSS, use the margin-top, margin-right, margin-bottom, and margin-left properties:

selector {
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 30px;
  margin-left: 40px;
}

You can also use the margin property, which combines the four properties from above into one:

selector {
  margin: 10px 20px 30px 40px;
}

Details

The margin properties increase or decrease the space outside of an element’s border. This is different than the padding properties, which increase or decrease the space around the content of the element inside the border. (Note: An element does not need to have a border set for the padding or margin properties to have an effect.)

All of the margin properties take length values.

margin

For the margin property, the order and number of values matters. It can have anywhere between one to four values.

One value applies to all four sides of the element(s):

selector {
  margin: 10px; /* All 4 sides */
}

With two values, the first value applies to the top and bottom and the second applies to the right and left:

selector {
  margin: 10px 20px; /* top, bottom | right, left */
}

With three values, the first value applies to the top, the second applies to the right and left sides, and the third value applies to the bottom:

selector {
  margin: 10px 20px 30px; /* top | right, left | bottom */
}

With four values, the first value applies to the top, the second to the right, the third to the bottom, and the fourth to the left:

selector {
  margin: 10px 20px 30px 40px; /* top | right | bottom | left */
}

Exercises

First, recreate the CSS code from the Demo section in your CSS file. Then try changing the values for the properties.

References

margin property on MDN

Back to: CSS Reference > CSS Properties