<h2>Using a New Block Formatting Context to Prevent Margin Collapse</h2>

<div class="container">
  <p> Sibling 1 </p>
  <p> Sibling 2 </p>
  <div class="c2 newBFC">
    <p> Sibling 3 </p>
  </div>
</div>

<button>TOGGLE BLOCK FORMATTING CONTEXT</button>

<p class="p">Demo by Ritesh Kumar. <a href="http://www.sitepoint.com/understanding-block-formatting-contexts-in-css" target="_blank">See article</a>.</p>
.container {
  background-color: red;
  overflow: hidden;
}

button {
  margin-top: 20px;
}

p {
  margin: 10px 0;
  background-color: lightgreen;
}

.newBFC {
  overflow : hidden;  /* triggers a new BFC */
}

/* general styling  */
body {
  text-align: center;
  width: 500px;
  margin: 20px auto;
}

.p {
  background: none;
  padding-top: 150px;
  font-size: 13px;
}
/* general styling ends */
var btn = document.querySelector('button'),
    c = document.querySelector('.c2');
btn.addEventListener('click', function () {
  c.classList.toggle('newBFC');
}, false);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.