gpt4 book ai didi

css - 为什么当 div 包含表格时不会发生边距折叠?

转载 作者:行者123 更新时间:2023-11-28 09:31:28 25 4
gpt4 key购买 nike

标题说明了一切。我浏览了 MDN page on margin collapsing ,从我读到的内容来看,在这种情况下,没有什么可以防止 marin 崩溃。您可以在下面看到它的实际效果,橙色框的高度为 82px (4*20+2),而我希望它的高度为 22px (20+2)。我错过了什么?

.outer { border: 1px solid orange }
.inner { margin-bottom: 20px }
<div class="outer">
<div class="inner"><table></table></div>
<div class="inner"><table></table></div>
<div class="inner"><table></table></div>
<div class="inner"><table></table></div>
</div>

最佳答案

来自 Mastering margin collapsing :

Margin collapsing occurs in three basic cases:

[…]

Parent and first/last child: If there is no border, padding, inline part, block formatting context created, […], then those margins collapse.

然后,Block formatting context文章说:

A block formatting context is created by at least one of the following:

[…]

  • anonymous table cells implicitly created by the elements with display: table, table-row, table-row-group, table-header-group, table-footer-group (which is the default for HTML tables, table rows, table bodies, table headers and table footers, respectively), or inline-table

所以一个<table>创建 block 格式化上下文。这就是利润率不会崩溃的原因。您可以更改 <table>进入<div>display: table;display: inline-block; (这也创建了一个 block 格式化上下文);这也将防止边距崩溃:

.outer { border: 1px solid orange }
.inner { margin-bottom: 20px }
.inner > div { display: table }
<div class="outer">
<div class="inner"><div></div></div>
<div class="inner"><div></div></div>
<div class="inner"><div></div></div>
<div class="inner"><div></div></div>
</div>

关于css - 为什么当 div 包含表格时不会发生边距折叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51202967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com