Margins & Whitespace

Hi!

So I was doing a CSS code challenge and got caught up on this (screenshot shows the correct solution). I thought that the bottom margin of the teal box and the top margin of the purple box would be added together to make the 100px space between them (or one box could have a margin of 100px and the other 0). I’m probably overlooking some simple explanation, but it’s driving me nuts trying to understand why this is the solution! I tried getting an answer from some other places such as THIS but haven’t had any luck. I appreciate any help. Thank you :slight_smile:

Please post a link to the exercise. We may have stored code that will help answer this.

We’re attempting to recreate from what is given.

<!DOCTYPE html>
<html>
<head>
  <title>Margin and Padding</title>
  <meta name="viewport" content="width=device-width,initial-scale=1" >
  <link href='style.css' rel='stylesheet'>
</head>
<body>
  <div id="teal"></div>
  <div id="purple"></div>
</body>
</html>

body {
  font-size: 100%;
  margin: 0;
  padding: 0;
  color: black;
  background: white;
}
div {
  width: 100px;
  height: 100px;
}
#teal {
  background: teal;
}
#purple {
  background: purple;
}

start_dimensions

That is what we start with. Now to fiddle with the margins and padding…

#teal {
  background: teal;
  margin: 100px;
  padding: 0 50px;
}
#purple {
  background: purple;
  margin: 50px 100px;
  padding: 50px;
}

What is going on here? Please give us your interpretation.

Hi again. I actually found my answer this morning after trying again. I hadn’t realized margin collapsing was a thing. THIS SOURCE was all I needed.

Thank you for your feedback!

If it wasn’t we’d be scrolling a lot more and have reams of whitespace on the page. It was in the plans to describe it once you gave your interpretation, but won’t be necessary now that you have done some follow-up reading.

Gotcha! I tried so many iterations of bottom and top margins for the boxes that I knew one of them wasn’t registering but I failed to understand why. So many resources talking about margins give examples where the whitespace in-between elements is the sum of their margins. I had to read a whole bunch on the box model for someone to even bring up margin collapse. From there I was able to look it up on MDN. On Codecademy, margin collapse isn’t taught until after that challenge (I see it’s upcoming on my syllabus in the new CSS section) so it didn’t occur to me that there are instances where margins “cancel” out. Makes great sense now though.

Padding doesn’t cancel out; it’s margins that collapse. They don’t cancel, but one is ignored. Margins are outside of the content box and padding is inside it.

Yes, I meant margins. Serves me right for going back into a lesson and then trying to respond to a forum message–words got jumbled!

Ignore is a better word. I meant “cancel” in the sense that one margin is prevented from going into effect by the larger margin or a margin of equal value.

1 Like