Why isn't the margin I set being applied to my elements?


#1

Question

Why isn’t the margin I set being applied to my elements?

Answer

This could happen for a few reasons including typos in our CSS declarations/document and setting margin-top or margin-bottom on a display: inline; element (as display: inline; elements do not respect margin-top/bottom;).

However, another common reason this may occur is because of collapsing margins. Collapsing margins happen when we have two or more adjacent margins (adjacent top and bottom margins only) on block level elements (display: block;), the adjacent margins combine into a single margin and will compute to the adjacent margin with the highest value.

For example, given the following HTML and CSS, we would expect the margin between .one and .two to be equal to 150px:

HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>My Site</title>
</head>
<body>
  <div class="one">block one</div>
  <div class="two">block two</div>
</body>
</html>

CSS:

div {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: lightpink;
}

.one {
  margin-bottom: 100px;
}

.two {
  margin-top: 50px;
}

But, when we factor in collapsing margins, we’ll remember that the margin that separates the two <div> elements will actually compute to 100px (the highest value of the adjacent margins).