让div重叠一个div重叠一个div

时间:2021-05-05 19:01:28

标签: html css position

我在这里有一个旧结构,我设法通过创建 DIV A1 absolute 和其他一些东西来解决,但我不再喜欢那个解决方案了。现在一定有更好的东西。

此示例中的结构未更改很重要。

问题:

  • DIV A 和 DIV B 是两个 DIV

  • DIV B1 在 DIV B 内

  • DIV B1 应该与 DIV A 重叠。可以用负边距和相对位置或类似的东西来实现。

  • DIV A1 在 DIV A 内

  • DIV A2 位于 DIV A1 内,类似于选择列表

问题 When the selectlist opens it should overlap DIV B1

.body {
  background-color: #eee;
}
.d {
  width: 100%;
  height: 200px;
}
.a {
  background-color: #f00;
}
.b {
  background-color: #00ff0036;
  width: 90%;
  margin: 0 auto;
}
.a1 {
  background-color: #0ff;
  width: 70%;
  height: 100px;
  margin: 0 auto;
  position: relative;
}
.a2 {
  background-color: #8dd7b8;
  width: 70%;
  height: 300px;
  margin: 0 auto;
  position: relative;
}
.b1 {
  background-color: #003cffb0;
  width: 70%;
  height: 200px;
  margin: 0 auto;
  position: relative;
  margin-top: -60px;
}
<div class="body">
  <div class="a d">A
    <div class="a1">A1
      <div class="a2">
        This DIV A2 needs to overlap the blue DIV B1.<br />At the moment it is under DIV B1.<br />While DIV B1 should keep overlapping DIV A.
      </div>
    </div>
  </div>

  <div class="b d">B
    <div class="b1">B1

    </div>
  </div>

</div>

显示所需最终结果的图像:

enter image description here

1 个答案:

答案 0 :(得分:0)

您已经回答了 99%。您只需要将 z-index: 10 添加到 .a2。因为它应该是一个前端元素。
z-index 属性指定元素的堆栈顺序,堆栈顺序较高的元素始终位于堆栈顺序较低的元素之前。

.body {
  background-color: #eee;
}
.d {
  width: 100%;
  height: 200px;
}
.a {
  background-color: #f00;
}
.b {
  background-color: #00ff0036;
  width: 90%;
  margin: 0 auto;
}
.a1 {
  background-color: #0ff;
  width: 70%;
  height: 100px;
  margin: 0 auto;
  position: relative;
}
.a2 {
  z-index: 10;
  background-color: #8dd7b8;
  width: 70%;
  height: 300px;
  margin: 0 auto;
  position: relative;
}
.b1 {
  background-color: #003cffb0;
  width: 70%;
  height: 200px;
  margin: 0 auto;
  position: relative;
  margin-top: -60px;
}
<div class="body">
  <div class="a d">A
    <div class="a1">A1
      <div class="a2">
        This DIV A2 needs to overlap the blue DIV B1.<br />At the moment it is under DIV B1.<br />While DIV B1 should keep overlapping DIV A.
      </div>
    </div>
  </div>

  <div class="b d">B
    <div class="b1">B1

    </div>
  </div>

</div>