Search code examples
cssparallax

Why doesn't margin work inside divs?


I'm working on my first parallax page and I found a simple example over at callmenick.

He has set his parallax.section to be 600px high. This is also the container for the images.

<section class="module content">
  <div class="container">    
    <h2>Lorem Ipsum Dolor</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
  </div>
</section>

<section class="module parallax parallax-2">
  <div class="container">
    <div class="test">Test container</div>
    <h1>Rise</h1>
  </div>
</section>

I've added a test div inside the container div with margin-top: 30px; I expected that it would create a 30 px margin between my test div and the container div. Instead it creates a gap between the section divs. Why is that?

If I add overflow: hidden to the container div, I solve this problem. But I still don't understand why margins don't work inside other divs.

You can see my fiddle here.

The css used is this:

section.module.parallax {
  height: 600px;
  background-position: 50% 50%;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

section.module .test{
    margin-top: 40px;
    background-color: #BCEF2F;
}

Solution

  • You're seeing collapsing margins. To fix it add overflow:auto to your container div:

    .container {
        max-width: 960px;
        margin: 0 auto;
        overflow:auto;
    }
    

    jsFiddle example