Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Min-height and margin

Tags:

css

Consider the following HTML:

.top {
  min-height: 150px;
}

p {
  margin: 50px;
}

div {
  background-color: #eee;
}
<div class="top">
  <p>Welcome</p>
</div>
<div class="content">Main content</div>

You can see it in action here:

http://jsfiddle.net/Lp4tp/1

Question

In Chrome(for Ubuntu), it appears that the margin defined on the p tag causes spacing between the top div and it's surrounding elements, instead of expanding the top div and producing the equivalent of adding 50 pixels padding on the top div.

Is this correct behavior? And if so, how can I ensure that child elements inside the top div cannot create undesired space between the top div and the content div.

Note

If I use a fixed height instead of a minimum height, the spacing between the top and the content div vanishes, but the top still produces 50 pixels of white space above itself.

like image 409
Niels B. Avatar asked Jan 16 '14 14:01

Niels B.


Video Answer


1 Answers

Your margins collapse. Fix with overflow:auto on the div:

div {
    background-color: #eee;
    overflow:auto;
}

jsFiddle example

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

You could also add a border to the div for the same result.

like image 175
j08691 Avatar answered Oct 21 '22 08:10

j08691