Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Margin issue with a wrapping DIV

Tags:

css

I am trying to wrap a div called content with another div that has a different background. However, when using "margin-top" with the content div, it seems like the wrapping DIV gets the margin-top instead of the content div.

Code:

<!DOCTYPE html>
<html>
  <head>
  <style>
    html {
        background-color:red;
    }
    #container-top {
        background-color: #ccc;
        overflow: hidden;
        padding-top: 10px;
        border-bottom: 1px solid #000;
        height:30px;
    }

    #container-bottom {
        background-color: #F1F4F2;
    }
    #content {
        margin-top:20px;
    }
    </style>
  </head>
  <body>
      <div id="container-top">
      </div>
      <div id="container-bottom">
          <div id="content">
              Hello
          </div>
      </div>
  </body>
</html>

So in the example, the div container-bottom gets the margin-top instead of the content div.

I found out that if I add a char inside container-bottom it fixes the issue.

  <div id="container-bottom">
      **A**
      <div id="content">
          Hello
      </div>

But of course that is not a good solution...

Thanks,

Joel

like image 729
Joel Avatar asked Mar 23 '26 07:03

Joel


2 Answers

What's happening is called margin-collapsing.

If two margins (top & bottom only, not right or left) of 2 elements are touching (or in your case, the top-margin of the inner div is touching the top-margin of the outer div), the max between them is used (in your case max(0, 20) = 20) and placed as far as possible from the touching elements (in your case outside the container div (the outermost element)).

To break this behavior, you have to place something between the 2 margins -> a padding at the top of the container div will do.

#container-bottom {
    background-color: #F1F4F2;
    padding-top: 1px;
}
#content {
    margin-top:19px;
}

other solution (works, but may not suit your needs):

you can simply put a padding-top of 20 px in the container div:

#container-bottom {
    background-color: #F1F4F2;
    padding-top: 20px;
}
#content {
}

for more informations, this page explains it very well: Margin Collapsing

like image 191
manji Avatar answered Mar 24 '26 19:03

manji


You could try adding a non-breaking space to the #container-bottom:

<div id="container-bottom">
    &nbsp;
    <div id="content">
        Hello
    </div>
</div>

This is a suitable solution as it is often used to let a browser know that an element is not empty (some browsers ignore empty elements).

like image 29
My Head Hurts Avatar answered Mar 24 '26 19:03

My Head Hurts