有什么方法可以让 CSS 边距通过字段集边界折叠?

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

在CSS中,相邻的垂直边距通常会相互“折叠”(即元素之间的垂直space将等于最大边距,而不是边距之和)。

但是,与大多数其他元素不同,fieldset 元素不允许其 child 元素上的边距与其兄弟元素上的边距折叠:

<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>

我认为(但不确定)这是因为字段集正在创建一个新的块格式化上下文 — the CSS spec doesn’t currently define whether fieldsets should or not, but the HTML5 spec says it “expects” them to

有什么方法可以防止 fieldsets 阻止他们的 children 和他们的兄弟姐妹之间的边缘崩溃?

正如您和@Blazemonger 已经在评论中讨论的那样,它可能是特定于浏览器的。如果您使用值为 group.

的 aria role 属性,您仍然可以使用 div 而不会牺牲可访问性
<div role="group">
  <!-- inputs here -->
</div>

来自官方规范:

WAI-ARIA provides a grouping role that functions similarly to fieldset and legend. In this example, the div element has role=group to indicate that the contained elements are members of a group and the aria-labelledby attribute references the id for text that will serve as the label for the group.

Source

是的,fieldset 元素建立了新的块格式化上下文(此行为首先在浏览器中实现,因此规范将此功能纳入 "expected default rendering")。

不幸的是,除了通过将 fieldset 元素的框设置为 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 来完全删除 fieldset 元素框外,我还不知道如何使用 CSS 来 "undo" ) .