简体   繁体   中英

Firefox adds margin on the wrong element

Today I came across this code. It works as I would expect in Chrome, but it is adding a margin on a wrong element with Firefox:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Site Title</title>
    <style type="text/css" media="screen">
    body {
      background-color: #aaa;
      margin: 0;
    }
    #header {
      background-color: #fff;
    }
    #logo {
      float: left;
    }
    #menu {
      float: right;
    }
    .container {
      width: 960px;
      margin: 0 auto;
    }
    .main {
      margin-top: 36px;
    }
    .clear {
      clear: both;
    }
    </style>
  </head>
  <body>
    <div id="header">
      <div class="container">
        <div id="logo">Logo</div>
        <div id="menu">Home</div>
        <div class="clear"></div>
      </div>
    </div>
    <div class="container main">
       Content
    </div>
  </body>
</html>

Firefox seems to add the margin in the .main rule to the content div, which was expected, and to the header div too.

If I add some text inside the header it would work as expected and the header won't have that margin:

<div id="header"> Some text here
  <div class="container">
    <div id="logo">Logo</div>
      <div id="menu">Home</div>
      <div class="clear"></div>
    </div>
  </div>
</div>

I can also add some text after the header block and it would also do the trick for Firefox.

I can't figure out why is Firefox adding that margin to the header element.

Very strange problem, I don't see why this happens.

It however seems to help when you add a padding of at least 1px to .container .

Also check this demo .

The problem has something to do with the container with automatic height and floating children...

Adding display:inline-block; to the #header will make it works in every browser (well except old IE), will include in the white box the right-floated div too (that now is not), and will continue to adjust the height automatically.

Fiddle: http://jsfiddle.net/AndreaLigios/VfAq7/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM