【问题标题】:Margin top causes parent div to fall [duplicate]边距顶部导致父 div 下降 [重复]
【发布时间】:2020-02-13 22:03:54
【问题描述】:

.d1 {
  background-color: lightblue;
}

.d2 {
  background-color: yellow;
  margin-top: 20px;
}
<div class="d1">
  <div class="d2">Test</div>
</div>

在这个简单的例子中,d1d2 的父元素。但是d2 会导致它自己和d1 拥有margin-top20px。为什么会这样?

【问题讨论】:

  • 您的代码运行良好。尝试在 d1 中添加一些内容,您会看到。现在你什么都没有,所以它没有显示并且 d2 离开了 margin-top。
  • 这是默认行为。这里提出了类似的问题。 stackoverflow.com/questions/1762539/…

标签: html css margin


【解决方案1】:

它的简单逻辑是,当您使用父 div 和子 div 时,父 div 将被子 div 样式覆盖,因为父将检查所有内部样式并给您输出。

示例: 如果您在 d1 和 d2 中都使用margin-top: 20px;,它将为您提供前 40px 的输出。

【讨论】:

    猜你喜欢
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 2012-04-08
    • 2020-09-12
    • 2012-07-26
    相关资源
    最近更新 更多