[margin top导致父div下降[重复]

问题描述 投票:4回答:1

此问题已经在这里有了答案:

.d1 {
  background-color: lightblue;
}

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

在此简单示例中,d1d2的父元素。但是d2会使自身和d1margin-top20px。为什么会这样表现?

html css margin
1个回答
-2
投票

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

示例:如果您同时在d1和d2中使用margin-top: 20px;,则会从前40个像素输出。


-2
投票

<!DOCTYPE html>
<html>
<head>
  <style>
  .d1 {
    background-color: lightblue;
  }
  .d2 {
    background-color: yellow;
      margin-top: 20px;
      padding-top: 10px;
  }
  body{
  margin: 0
  }
  </style>
</head>
<body>
  <div class="d1">
    <div class="d2">Test</div>
  </div>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.