Collapsing Margins 1

by Richard Hunter

HTML

<h1>Collapsing Margins 1</h1>
<div class="bar"></div>
<div id="container" class="container block-formatting-context">
</div>
<div class="foo"></div>
<button id="toggle"> toggle block formatting context</button>
<p>
Two margins are adjoining if and only if: ...top and bottom margins of a box that does not establish a new block formatting context and that has zero computed 'min-height', zero or 'auto' computed 'height', and no in-flow children
</p>
https://www.w3.org/TR/CSS22/box.html#collapsing-margins
<p>Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.</p>
https://www.w3.org/TR/CSS22/visuren.html#block-formatting

SCSS

.container {
  background: pink;
  margin-top: 30px;
  margin-bottom: 30px;
}
.bar,
.foo {
  background: red;
  padding: 15px;
}
.block-formatting-context {
  overflow: auto; // creates new block formatting context
}

JavaScript

toggle.addEventListener('click', function () {
	container.classList.toggle('block-formatting-context');
});