tags:

views:

45

answers:

2

Hi, could someone answer me, WHY when I set a margin-top to my <div id="logo">, all the others divs are pushed down. And why if a set float:left to my <div id="logo">, everything works fine.

Code:

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <title>Olá Mundo!</title>
    <style>
      /* CSS RESET HERE */ ( http://html5doctor.com/html-5-reset-stylesheet/ )
      body { margin:0; }
      #container { width:1000px; min-height:100%; height:auto; margin:0 auto; }
      #header { width:100%; height:160px; background-color:#FF0; }
      #logo { width:150px; height:150px; margin:10px 0 0 10px; background-color:#F0F; }
    </style>
  </head>
  <body>

    <div id="container">
      <div id="header">

        <div id="logo">
          <h1>Minha logo!</h1>
          <h2>meu slogan ...</h2>
        </div>

      </div>

  </body>  
</html>
+2  A: 

Your h1 has a default margin on them (on safari on my computer it's .67em). This is what's causing everything to be pushed down.

try:

h1{margin:0;}

Will fix everything.

The reason it works when you float is that floating it takes the logo element out of the normal flow, so it doesn't affect its parents' positioning.

Also, I ALWAYS use a reset css to avoid this. YUI's reset works very well.

brad
Oh, sorry about that. I'm using the css set/reset created by Richard Clark ( http://html5doctor.com/html-5-reset-stylesheet/ ).Thanks for the answer!
Lips
ugh, well my answer WAS right with the original question :(
brad
+2  A: 

It's caused by margin collapse.

Normal Document Flow

In the case where <div id="logo"> is not floated, its top margin is actually sticking out of the top of its containing element, which pushes everything down. The reason for this behavior (as the article above points out) is so that if you have a series of paragraphs with the following CSS:

p {
   margin: 1em 0;
}

They will only have 1em of margin between them, instead of 2em (which would be the result if margins didn't collapse).

Float Fix

When you float <div id="logo"> it takes it out of the normal document flow, which means its top margin no longer collapses with its parent's margin.

Fixes

Other options to fix margin collapse in your case would be to add 1px of top/bottom padding or a border to your <div id="header">.

Pat
Thaaaaanks for the answer! I'm reading the article, ty very much :D
Lips