我注意到 div 标签有一个奇怪的行为(根据我对 HTML 和 CSS 的了解,我认为)。 我正在构建一个带有自定义网格系统的网站,如果我不应用 float 属性(左或右),我在其中应用网格类的 div 将不会注意到边距属性。
代码:
.grid-100 {width: 100%;}
.grid-60 { width: 65%; float: left;}
.grid-30 { width: 33%; float: left;}
.grid-100, .grid-60, .grid-30 { margin-top: 30px;}
如果我不将 float:left;
设置为 .grid-100,则具有此类的 div 不会将 margin-top 应用到 30px。
谁能给我解释一下?
最佳答案
参见 margin collapsing .
正常行为是:
Parent and first/last child
If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
当你漂浮它们时:
Margins of floating and absolutely positioned elements never collapse.
关于html - div 属性的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24249944/