首页 > 解决方案 > 更改 html/css 中元素顺序的问题

问题描述

我有两个元素作为父元素和子元素,我想让子元素落后于父元素。我尝试将 z-index:-1 添加到子元素但没有任何反应……有人可以指导我如何让子元素落后于父元素。

.parent {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: coral;
  color: white;
  font-size: 25px;
  text-align: center;
  line-height: 200px;
  cursor: pointer;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: silver;
  z-index: -1;
}
<div class="parent">
  parent
  <div class="child">child</div>
</div>

标签: htmlcss

解决方案


这里的问题是,当您设置transform除 之外的属性时none,您在 CSS 中定义了一个新的堆叠上下文。删除此属性可解决此问题。1 .

    .parent {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: coral;
  color: white;
  font-size: 25px;
  text-align: center;
  line-height: 200px;
  cursor: pointer;
  position: absolute;
  top: 50%;
  left: 50%;
/*  transform: translate(-50%, -50%);
*/  
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: silver;
  z-index: -1;
}
<div class="parent">parent
    <div class="child">child</div>
  <div>


推荐阅读