首页 > 解决方案 > 将绝对元素放在兄弟元素下

问题描述

我想在它的兄弟下放置一个自定义按钮元素,以便兄弟的阴影效果在按钮上可见。目前阴影在按钮上不可见,但在其下方。请参阅代码片段以更好地理解我的意思:

.parent {
  position: absolute;
}

.box {
  width: 200px;
  height: 40px;
  background-color: white;
  box-shadow: 1px 0px 20px 0px rgba(0, 0, 0, 0.18);
  z-index: 10;
}

.button {
  height: 20px;
  width: 20px;
  background-color: white;
  text-align: center;
  position: absolute;
  right: -20px;
  top: 10px;
  z-index: 1;
}
<div class="parent">
  <div class="box"></div>
  <div class="button">x</div>
</div>

标签: css

解决方案


应用position: relative;.box,使其支持 z-index 值而不影响布局。

.box {
  width: 200px;
  height: 40px;
  background-color: white;
  box-shadow: 1px 0px 20px 0px rgba(0, 0, 0, 0.18);
  position: relative;
  z-index: 10;
}

另一种选择是将z-index.button 更改为-1。但它可能会对布局产生其他影响,因为该元素将位于所有其他元素的后面。

.button {
  height: 20px;
  width: 20px;
  background-color: white;
  text-align: center;
  position: absolute;
  right: -20px;
  top: 10px;
  z-index: -1;
}

推荐阅读