nalzok
nalzok

Reputation: 16107

How can a border cause margins to collapse?

Please take a look at the following examples:

.wrapper {
  width: 740px;
  background: #ccc;
}
.leftSidebar {
  float: left;
  width: 200px;
}
.mainContent {
  padding-right: 200px;
  padding-left: 200px;
}
<div class="wrapper">
  <div class="leftSidebar">
    <h2>Heading</h2>
    <pre>.leftSidebar {
  float:left;
  width:200px;
}</pre>
  </div>
  <div class="mainContent">
    <h2>Heading</h2>
    <pre>.mainContent {
  padding-right:200px;
  padding-left:200px;
}</pre>
  </div>
</div>

.wrapper {
  width: 740px;
  background: #ccc;
}
.leftSidebar {
  float: left;
  width: 200px;
}
.mainContent {
  padding-right: 200px;
  padding-left: 200px;
  border: 1px solid rgba(0, 0, 0, 0);
}
<div class="wrapper">
  <div class="leftSidebar">
    <h2>Heading</h2>
    <pre>.leftSidebar {
  float:left;
  width:200px;
}</pre>
  </div>
  <div class="mainContent">
    <h2>Heading</h2>
    <pre>.mainContent {
  padding-right:200px;
  padding-left:200px;
  border: 1px solid rgba(0, 0, 0, 0);
}</pre>
  </div>
</div>

As you can see above, a transparent border of mainContent changes the layout in a significant way.

Here is my idea about what's happening: For some reasons, the border: 1px solid rgba(0, 0, 0, 0); applied on mainContent causes the floating leftSidebar's margin to collapse with the margin of mainContent, just like what a display: inline-block applied on mainContent would do.

However, I don't know the details. The relevant part of CSS 2.1 is too hard for me to understand. Can someone tell me why and how exactly the collapsing happens?

Upvotes: 1

Views: 42

Answers (1)

BoltClock
BoltClock

Reputation: 723688

The border isn't causing the margins of .mainContent to collapse with those of .leftSidebar. It's preventing the margins of its descendants from collapsing with itself (and therefore with .wrapper). That's why the top margin of .mainContent > h2 is now aligned with that of .leftSidebar > h2 — the reason the descendant margin of .leftSidebar similarly isn't collapsing with itself or .wrapper is because it's floating.

.mainContent and .leftSidebar are side by side, so there's no way their descendant margins could be considered adjoining, and so there's no way their descendant margins could collapse with one another.

Upvotes: 2

Related Questions