CSS Margins

The margin properties add transparent space around the outside of an element, pushing neighboring content away.

Margin is the outermost layer of the box model. It clears an area outside the border, and because it is fully transparent, whatever is behind the element shows through. Margin is often used to space paragraphs, cards, and sections apart from each other.

Setting each side

You can control every edge on its own with <margin-top>, <margin-right>, <margin-bottom>, and <margin-left>. Each one accepts a length such as px or rem, a percentage of the parent's width, or the keyword auto.

One side at a time

<!DOCTYPE html>
<html>
<head>
<style>
.card {
  margin-top: 24px;
  margin-right: 16px;
  margin-bottom: 24px;
  margin-left: 16px;
}
</style>
</head>
<body>

<div class="card">Card one</div>
<div class="card">Card two</div>

</body>
</html>

The shorthand

The <margin> shorthand lets you set all four sides in one declaration. The number of values you pass changes which sides they apply to.

ValuesMeaning
margin: 20pxAll four sides get 20px
margin: 10px 30pxTop/bottom 10px, left/right 30px
margin: 5px 10px 15pxTop 5px, left/right 10px, bottom 15px
margin: 5px 10px 15px 20pxTop, right, bottom, left in clockwise order

Centering a block

<!DOCTYPE html>
<html>
<head>
<style>
.container {
  width: 600px;
  margin: 0 auto;
}
</style>
</head>
<body>

<div class="container">
  <p>This block is centered horizontally.</p>
</div>

</body>
</html>
Note: Setting the left and right margins to auto on a block element with a fixed width centers it horizontally inside its parent.

Margin sits just outside the padding and border. If you are new to how those layers fit together, read the CSS Box Model page next.

Exercise: CSS Margins

In the shorthand `margin: 10px 15px 5px 20px;`, what order are the four values applied in?