我可以让一个不相关的元素出现在父母和孩子之间吗

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

我有一个包含另一个元素的元素,由于代码中的其他部分,很难在不破坏东西的情况下断开这两个元素。我有一个不相关的元素,孩子需要出现在上面,但父母应该出现在下面。

下面的代码是对我的尝试和 chatgpt 问题的再现,不相关的元素仍然出现在父母和孩子的上方。

<style>
.parent {
  position: relative;
  background-color: #ccc;
  height: 100px;
  width: 100px;
  z-index: 1;
}

.child {
  background-color: #f00;
  height: 50px;
  width: 50px;
  z-index: 3;
}

.unrelated {
  position: absolute;
  top: 25px;
  left: 25px;
  background-color: #00f;
  height: 25px;
  width: 50px;
  z-index: 2;
}

</style>
<div class="parent">
  <div class="child">
    Child element
  </div>
</div>

<div class="unrelated">
  Unrelated element
</div>

有什么办法可以让不相关的元素出现在它们之间?

html css
1个回答
1
投票

position: relative
上的
.parent
正在定义一个新的 stacking context – 只要它存在,
.parent
.child
将独立于
.unrelated
堆叠在一起。

在您的玩具示例中,只需从

position: relative
中删除
.parent
并将其添加到
.child
即可实现所需的布局。在您的最终代码中,您还需要删除在
.child
和它与
.unrelated
最近的共同祖先之间创建新堆叠上下文的任何规则。不幸的是,这可能会导致很多混乱的重新定位。

<style>
.parent {
  position: static;
  background-color: #ccc;
  height: 100px;
  width: 100px;
}

.child {
  position: relative;
  background-color: #f00;
  height: 50px;
  width: 50px;
  z-index: 3;
}

.unrelated {
  position: absolute;
  top: 25px;
  left: 25px;
  background-color: #00f;
  height: 25px;
  width: 50px;
  z-index: 2;
}

</style>
<div class="parent">
  <div class="child">
    Child element
  </div>
</div>

<div class="unrelated">
  Unrelated element
</div>

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