chukwuemeka aigbokhan
chukwuemeka aigbokhan

Reputation: 71

HTML and CSS --- margin Problems

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>

Upvotes: 1

Views: 57

Answers (1)

andreas
andreas

Reputation: 16936

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>

Upvotes: 2

Related Questions