如何将子元素移动到位于其父元素之上的父元素的另一个子元素之上?

时间:2017-07-13 07:10:26

标签: html css

我有两个父元素(黑色和红色div s)。它们每个都包含一个子元素。黑色包含灰色div。红色的包含粉红色的div。

遵循约束:

  • 我无法改变孩子与其父元素之间的关系,即我不能将子元素移到它自己的父元素之外。
  • 红色div必须保留在黑色div下面

是否可以将粉色div移动到灰色div上方?



.parent-black {
  width: 100%;
  height: 50px;
  background-color: rgba(0, 0, 0, .9);
  color: white
}

.child-gray {
  width: 250px;
  height: 90px;
  background-color: gray;
  position: absolute;
  right: 137px;
  top: 20px;
  z-index: 0;
  color: white;
}

.parent-red {
  width: 100%;
  height: 40px;
  background-color: red;
  position: absolute;
  top: 40px;
  z-index: -999;
}

.child-pink {
  width: 95%;
  height: 80px;
  background-color: pink;
  top: 30px;
  left: 20px;
  position: absolute;
  z-index: 9999;
}

<div class="parent-red">
  2
  <div class="child-pink">2.1</div>
</div>
<div class="parent-black">
  1
  <div class="child-gray">1.1</div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

使用下面的jQuery

&#13;
&#13;
$(document).ready(function() {
  $('.child-gray').insertBefore($('.child-pink'));
})
&#13;
.parent-black {
  width: 100%;
  height: 50px;
  background-color: rgba(0, 0, 0, .9);
  color: white
}

.child-gray {
  width: 250px;
  height: 90px;
  background-color: gray;
  position: absolute;
  right: 137px;
  top: 20px;
  z-index: 0;
  color: white;
}

.parent-red {
  width: 100%;
  height: 40px;
  background-color: red;
  position: absolute;
  top: 40px;
  z-index: -999;
}

.child-pink {
  width: 95%;
  height: 80px;
  background-color: pink;
  top: 30px;
  left: 20px;
  position: absolute;
  z-index: 9999;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent-red">
  2
  <div class="child-pink">2.1</div>
</div>
<div class="parent-black">
  1
  <div class="child-gray">1.1</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

老实说,我在这里没有得到真正的问题...我想这符合你的约束:

.parent-black {
  width: 100%;
  height: 50px;
  background-color: rgba(0, 0, 0, .9);
  color: white;
  position: relative;
}

.child-gray {
  width: 250px;
  height: 90px;
  background-color: gray;
  position: absolute;
  right: 137px;
  top: 20px;
  z-index: 0;
  color: white;
}

.parent-red {
  width: 100%;
  height: 40px;
  background-color: red;
  margin-top: -20px;
}

.child-pink {
  width: 95%;
  height: 80px;
  background-color: pink;
  top: 70px;
  left: 20px;
  position: absolute;
  z-index: 9999;
}
<div class="parent-black">
  1
  <div class="child-gray">1.1</div>
</div>
<div class="parent-red">
  2
  <div class="child-pink">2.1</div>
</div>