Felipe Miosso
Felipe Miosso

Reputation: 7339

HTML margin push other elements

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>

Upvotes: 6

Views: 4915

Answers (2)

Pat
Pat

Reputation: 25675

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">.

Upvotes: 7

brad
brad

Reputation: 32335

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.

Upvotes: 2

Related Questions