javascript - 子元素的边距

标签 javascript css

<分区>

Possible Duplicate:
Margin on child element moves parent element

我有一个包含子 div 的父 div。 Parent 是正文中的第一个元素,没有特定的 CSS 样式。当我设置

.child {
   margin-top: 10px;
}

最终结果是 child 的顶部仍然与 parent 对齐。不是 child 向下移动 10px,而是我的 parent 向下移动 10px。

我发现向 parent 添加填充可以工作,但我读到这不是解决问题的方法。为什么?如果我想要 margin-right 我可以在 parent 上做 padding-right,同样如果我想要 margin-top我也可以执行 padding-top 并获得正确的结果。

margin on child element moves parent element有人说:

What if you want a top-margin...? Not really a solution. This isn't really a solution if a top margin is required.

他想表达什么?请解释。

最佳答案

来自 CSS Margin Collapsing在 Mozilla 开发者网络上:

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 [...] then those margins collapse. The collapsed margin ends up outside the parent.

关于javascript - 子元素的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14110488/

上一篇:javascript - Canvas 宽度和高度计算已关闭

下一篇:css - 图片布局空间大的div位置

相关文章:

javascript - 在 javascript 中添加两个被 HTML 包围的变量

html - 背景图像重复页面的全高?

html - 粘性页脚问题(我看过)

html - 使用 Chrome 进行 IE 8 测试

php - 子主题未从父主题加载整个样式

javascript - 使用 Javascript 在 chartjs 中动态更新图表的选项

javascript - Node.js:创建一个 txt 文件而不写入设备

javascript - 禁用动态创建的下拉选择列表选项

javascript - CodeIgniter - 表单加载

javascript - 如何适应高度为 :100% on iPhone 的 DIV