1

If you place a margin-top on the first box (red_box) it pulls or affects the containing box (container). Why?

.red_box {
  background-color: red;
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 20px;`
  margin-left: 40px;
  height: 100px;
  width: 300px
}

.green_box {
  background-color: green;
  margin-top: 40px;
  margin-right: 20px;
  margin-bottom: 20px;
  margin-left: 40px;
  height: 100px;
  width: 300px
}

.container {
  width: 500px;
  height: 500px;
  background-color: yellow;
}
<div class="container">
  <div class="red_box">
    red box
  </div>
  <div class="green_box">
    green box
  </div>
</div>

1 Answer 1

2

The reason for this behaviour is margin collapsing:

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin.

You can prevent it with an overflow rule on the .container:

.red_box {
  background-color: red;
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 20px;`
  margin-left: 40px;
  height: 100px;
  width: 300px;
}

.green_box {
  background-color: green;
  margin-top: 40px;
  margin-right: 20px;
  margin-bottom: 20px;
  margin-left: 40px;
  height: 100px;
  width: 300px
}

.container {
  width: 500px;
  height: 500px;
  background-color: yellow;
  overflow: hidden; /* <-- this prevents margin collapsing */
}
<div class="container">
  <div class="red_box">
    red box
  </div>
  <div class="green_box">
    green box
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.