html - div 属性的行为

标签 html css

我注意到 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/

相关文章:

css - 如何在高对比度模式下显示 CSS 按钮

html - 嵌套 Div 使按钮围绕电话 : Link?

javascript - 单击事件未触发。我的代码有什么问题吗?

html - 图像不工作

css - 如果“Angular Material ”按钮中的文本长于按钮的宽度,该如何打断单词?

html - Div里面显示:table-row section not expanding to full width

jquery - 实现 datepicker jquery UI 时出错

html - CSS3 @font-face 不能使用受版权保护的字体或某些字体吗?

jquery - anchor 标记在移动浏览器中不起作用

javascript - 检查注册表中的用户名