CSS Tutorial menu

CSS Margin and Padding

Margin and padding both add space, but in different places.

Margin vs Padding

  • Padding is the space inside an element, between its content and its border
  • Margin is the space outside an element, between its border and other elements

A background colour fills the padding but not the margin.

Example

html
<!DOCTYPE html>
<html>
<head>
<style>
.box {
  background-color: #dbe4ff;
  border: 2px solid #264de4;
}
.padded {
  padding: 30px;
}
.spaced {
  margin: 30px;
}
</style>
</head>
<body>

<div class="box">No padding, no margin</div>
<div class="box padded">30px padding (space inside)</div>
<div class="box spaced">30px margin (space outside)</div>

</body>
</html>
Try it Yourself »

Setting Each Side

Both properties have a version for each side:

MarginPadding
margin-toppadding-top
margin-rightpadding-right
margin-bottompadding-bottom
margin-leftpadding-left

Example

css
.card {
  padding-top: 10px;
  padding-bottom: 20px;
  margin-left: 15px;
}

The Shorthand

You can set all sides in one line. The number of values decides which sides they go to. Think of a clock: top, right, bottom, left.

ShorthandTopRightBottomLeft
padding: 10px;10px10px10px10px
padding: 10px 20px;10px20px10px20px
padding: 10px 20px 5px;10px20px5px20px
padding: 10px 20px 5px 0;10px20px5px0

The same rules work for margin.

Centring a Box with auto

If a block element has a width, margin: 0 auto puts it in the centre. The browser shares the free space equally on the left and right.

Example

html
<!DOCTYPE html>
<html>
<head>
<style>
.form-box {
  width: 300px;
  margin: 20px auto;
  padding: 20px;
  background-color: #f8f9fa;
  border: 1px solid #cccccc;
}
</style>
</head>
<body>

<div class="form-box">
  <h3>Student Login</h3>
  <p>This box is centred on the page.</p>
</div>

</body>
</html>
Try it Yourself »

Margin Collapse

When two vertical margins touch, they do not add together. The larger one wins. If one paragraph has margin-bottom: 20px and the next has margin-top: 30px, the gap between them is 30px, not 50px. This only happens with top and bottom margins, never with left and right, and never with padding.

Padding cannot be negative, but margin can. A negative margin pulls an element closer to its neighbour. Use it carefully, because it can make elements overlap.

Exercise

Exercise

What does margin: 10px 20px; do?

Learn CSS with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp