Šime Vidas
Šime Vidas

Reputation: 185893

CSS: Adding a border changes the background-color (?!)

HTML:

<div> <p></p> </div> 

CSS:

div { background-color:green; border-top:1px solid white; }
p { background-color:yellow; height:50px; margin:70px; } 

Demo: http://www.jsfiddle.net/Xy8QF/4/

Why is the area above the yellow paragraph green, and the area bellow it white?

btw I already figured this out, but I thought I'll post this anyway. Consider it a riddle :)


Update: Just to add to the accepted answer:

  1. Only vertical margins collapse
  2. The margins will not collapse if the outer element (in this case the DIV) has a padding or border

Upvotes: 4

Views: 3059

Answers (4)

Charlie Martin
Charlie Martin

Reputation: 112356

It's because the <p> is right against the bottom of the enclosing <div>. Since there's nothing constraining the height of the <div>, the rendering gives just enough space to fit down to the bottom of the <p>. Any explicit height > 50px will show the bottom.

Yup, on the update, exactly. The box expands vertically, but not horizonally. Also, padding puts space on the inside of the box, so the p can't push right up against the bounds.

Read up on the CSS box model, for example here: http://www.w3schools.com/css/css_boxmodel.asp and here: http://www.w3.org/TR/CSS21/box.html

Upvotes: 0

phihag
phihag

Reputation: 287775

This happens because the margins of two block elements with position:static (the default) collapse as per CSS 2.1 8.3.1, i.e. the margin is "carried over" to the body element. This demo shows it does not happen with absolutely positioned elements, one of the exceptions (along with a non-none border) listed in the aforementioned standard.

Upvotes: 5

DigiKev
DigiKev

Reputation: 1071

The area above the yellow paragraph as you put it, is not actually above it. The green div contains the yellow paragraph. The yellow paragraph has a margin of 70px, pushing away from the green edges of its container. The yellow paragraph has a height set to it, hence we cannot see the yellow pushing away from the green on the bottom edge.

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116100

Good question. :) You can solve it by giving the div a bottom border, or if you don't want to, by giving it a height of 100%. ;-)

Upvotes: 1

Related Questions