0

I'm struggling with a strange behaviour of some CSS block elements in a plain HTML document. Depending on whether an element has a border or not, the behaviour of CSS property margin-top changes.

See this jsFiddle and click on the appropriate sections to watch what happens. For example, click on the first section. Here you will see, how margin-top: 40px; of the h2 element stops to work if the section has 0px border.

How to fix this?

The HTML-Code:

<div class="topbar">
    <h1>Hello world!</h1>
</div>
<div class="page-wrapper">
    <section class="page-section">
        <h2>What happens here?</h2>
    </section>
    <section class="page-section">
        <h2>Different Section</h2>
    </section>
</div>

The CSS-Code

body{
    margin:0;
    padding:0;
}
.topbar{
    position: fixed;
    top: 0px;
    width: 100%;
    height: 60px;
    text-align: center;
    border: 1px solid silver;
}
.page-wrapper{
    margin-top: 60px;
    border: 1px solid red;
}
.page-section{
    height: 200px;
    border: 1px solid blue;
}
.page-wrapper.active,
.page-section.active{
    border: 0px;
}
.page-section h2{
    margin-top:40px;
}

And some jQuery just to toggle div borders:

$(document).ready(function(){
    $('.page-section').click(function(){
        $(this).toggleClass('active');
        $('.page-wrapper').toggleClass('active');
    });
});
Bunjip
  • 297
  • 5
  • 14
  • 4
    Read about [Margin Collapsing](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing) – Mohammad Usman Aug 31 '16 at 10:06
  • Margin collapsing is new to me. So thanx for sharing, @MuhammadUsman. Duplicate question issue accepted, too. – Bunjip Aug 31 '16 at 10:19

0 Answers0