neodymium
neodymium

Reputation: 3936

Why does adding a border change the behavior of the background color?

In the example below why does removing the border on the #enclosing div make the background lightblue color not fill the entire div background anymore?

#enclosing
{
  background: lightblue;
  margin: 0;
  border: 1px solid blue;
}

#outer
{
  margin: 40px;
}

#inner
{
  margin: 20px;
  border: 1px solid black;
}​

<div id="enclosing">
    <div id="outer">
      <div id="inner">This is nested div</div>
    </div>
</div>

Example also on JSFiddle

Upvotes: 1

Views: 68

Answers (1)

random_user_name
random_user_name

Reputation: 26160

The outer div has margin, which needs something to "push" against.

When the enclosing div has no border (or padding), there is nothing for the margin of the outer div to push against.

Adding border or padding to the top/bottom of the div gives it the necessary containment for the outer div to calculate off of.

I believe this is what's known as collapsing margins in the Box Model

Upvotes: 2

Related Questions