CSS 负边距,为什么重叠在背景上而不是内容中

问题描述 投票:0回答:2

当对元素应用负边距时,为什么文本 1 位于子 2 的背景上方并位于文本后面,我认为它将位于整个框的后面。

html {
  font-size: 40px;
  font-weight: bold;
}

.child1 {
  color: white;
  background-color: red;
}

.child2 {
  color: black;
  background-color: green;
  margin: -35px 0 0 20px;
}
<body>
  <div>
    <div class="child1">text 1 some text here</div>
    <div class="child2">text 2 other text here</div>
  </div>
</body>
html css margin
2个回答
0
投票
<!DOCTYPE html>
<html>
<head>
<style>
  html {
    font-size: 40px;
    font-weight: bold;
  }

  .child1 {
    color: white;
    background-color: red;
    position: relative; /* Create stacking context */
    z-index: 2; /* Ensure it is above .child2 */
  }

  .child2 {
    color: black;
    background-color: green;
    margin: -35px 0 0 20px;
    position: relative; /* Ensure it is part of stacking context */
    z-index: 1; /* Ensure it is below .child1 */
  }
</style>
</head>
<body>
  <div>
    <div class="child1">text 1 some text here</div>
    <div class="child2">text 2 other text here</div>
  </div>
</body>
</html>

0
投票

您可以使用 css

z-index
属性简单地将整个 .child2 框移动到 .child1 elt 上:

.child2 {
  ...
  position: relative;
  z-index: 2;
}

完整示例:

html {
  font-size: 40px;
  font-weight: bold;
}

.child1 {
  color: white;
  background-color: red;
}

.child2 {
  color: black;
  background-color: green;
  margin: -35px 0 0 20px;
  position: relative;
  z-index: 2;
}
<body>
  <div>
    <div class="child1">text 1 some text here</div>
    <div class="child2">text 2 other text here</div>
  </div>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.