One interesting CSS behavior is that adjacent vertical margins typically collapse into one another. In other words, the space between elements will be equal to the larger margin instead of the sum of both margins.
Interestingly, fieldset
elements do not follow this rule like most other elements. Margins on child elements within a fieldset do not collapse with margins on their sibling elements:
<div>Before div</div>
<div style="margin:0; border:0; padding:0; background:#ccc;">
<div style="margin:20px 0;">This div has top and bottom margins that cannot collapse outside of the parent div.</div>
</div>
<div>After div</div>
<div>Before fieldset</div>
<fieldset style="margin:0; border:0; padding:0; background:#ccc;">
<div style="margin:20px 0;">This div also has top and bottom margins, but the parent fieldset prevents them from collapsing.</div>
</fieldset>
<div>After fieldset</div>
The reason for this behavior might be because the fieldset creates a new block formatting context. Although the CSS specification does not clearly define whether fieldsets should create a new block formatting context or not, the HTML5 specification "expects" them to do so.
Is there a way to override or prevent fieldsets from blocking the collapsing of margins between their children and siblings?