Search code examples
cssmarginfieldset

Is there any way to allow CSS margins to collapse through a fieldset boundary?


In CSS, adjacent vertical margins usually “collapse” into one another (i.e. the vertical space between the elements will be equal to the largest margin, not the sum of the margins).

However, fieldset elements, unlike most other elements, do not allow margins on their child elements to 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 a top and bottom margin, which has collapsed 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 has a top and bottom margin, but the parent fieldset prevents it from collapsing.</div>
</fieldset>
<div>After fieldset</div>

I think (but am not sure) that this is because the fieldset is creating a new block formatting context — the CSS spec doesn’t currently define whether fieldsets should or not, but the HTML5 spec says it “expects” them to.

Is there any way to prevent fieldsets from blocking the collapsing of margins between their children and their siblings?


Solution

  • Yes, the fieldset element establishes the new block formatting context (this behavior was first implemented in the browsers, so the spec incorporated this feature as part of "expected default rendering").

    Unfortunately, I don't know any way to "undo" this with CSS, except completely removing the fieldset element's box by setting it to display:contents, which currently only gives the desired result in Chrome with the "Experimental Web Platform features" flag turned on (Firefox, although implemented display:contents back in 2015, hasn't updated its implementation to work for "unusual elements" like form controls according to the recent addition to the spec yet).