【问题标题】:Placing child element on top of sibling element将子元素放在兄弟元素之上
【发布时间】:2021-07-10 08:56:40
【问题描述】:

我想将我的子元素放在我的兄弟元素之上,而不更改任何书面 css。我可以添加任何额外需要的东西,但不能删除任何东西。

HTML:

<div class='sibling'>
  <div class='child'>
  </div>
</div>

<div class='sibling'>
</div>

CSS

.sibling{
  width:40px;
  height:40px;
  position:sticky;
  border:1px solid black;
  background:green;
  margin:4px;
}

.child{
  width:30px;
  height:100px;
  border:1px solid red;
  background:red;
}

【问题讨论】:

  • 听起来你只需要给第二个兄弟一个比第一个低的z-index
  • 拥有大量兄弟姐妹并为每个兄弟姐妹分配 z 索引似乎不是一个好方法?有没有其他办法?
  • 向每个兄弟姐妹添加一个类(或使用现有类)并添加具有较低 z-index 的 CSS 规则对我来说似乎是一个非常简单的解决方案。还有其他解决方案,但我想不出任何像设置z-index 这样简单的解决方案。

标签: html css css-position z-index


【解决方案1】:

您可以通过将第二个 sibling 类型元素的 z-index 低于第一个元素来实现这一点,如下所示:-

.sibling{
  width:40px;
  height:40px;
  position:sticky;
  border:1px solid black;
  background:green;
  margin:4px;
}

.sibling:nth-of-type(1){
  z-index:2
}

.sibling:nth-of-type(2){
  z-index:1;
}

.child{
  width:30px;
  height:100px;
  border:1px solid red;
  background:red;
}
<div class='sibling'>
  <div class='child'>
  </div>
</div>

<div class='sibling'>
</div>

【讨论】:

  • 拥有大量兄弟姐妹并为每个兄弟姐妹分配 z 索引似乎不是一个好方法?有没有其他办法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 2022-01-17
  • 2013-01-01
  • 2015-01-14
  • 1970-01-01
  • 2019-09-15
相关资源
最近更新 更多