gdbj gdbj - 1 month ago 6
CSS Question

Margin collapse between IMG and H2 element not working

Is there a reason why the vertical margin between an image and h2 isn't collapsing? I have the following code and style. From all the reading, there is no exception due to it being an img tag. Is it because an IMG is technically in-line? In Chrome at least, it has a top and bottom margin added. Is it better practice to wrap the image in a block element?

<section id="test">
<img src="img/web_dev2@2x.png"/>
<h2>Test</h2>
</section>


Style:

img, h2 {
margin: 2em 0;
}


-- EDIT:
When I wrap the img with a P tag and apply margin to it instead, the margin collapses, as expected. What is best practice then?

Answer

Margin only collapses between blocks:

Two margins are adjoining if and only if:

But images are inline-level by default. Blockify it:

img, h2 {
  display: block;
  margin: 2em 0;
}
<section id="test">
  <img src="/favicon.ico"/>
  <h2>Test</h2>
</section>