设置子元素的Z索引小于父元素而不隐藏它

问题描述 投票:0回答:1

我有一个父级

div
,它有一个背景图像(只有一条对角线的 SVG)。 我的孩子
div
将有一些背景颜色,具体取决于变量的值。 我想在我的孩子
div
背景颜色上显示父级背景图像(对角线)。

自然地,我求助于使用 z-index。但这不起作用。为子

z-index : -1
设置
div
会完全隐藏它(我认为发生这种情况是因为它位于根 div 本身的后面)。

我的限制是我不能将父级或子级 div 都定位为

absolute
,否则我的布局会很混乱(将它们定位为相对 z-index 才能生效)

<div style="background-image:url(&quot;data:image/svg+xml,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20version%3D'1.1'%20preserveAspectRatio%3D'none'%20viewBox%3D'0%200%2010%2010'%3E%20%3Cpath%20d%3D'M%2010%200%20L%200%2010'%20fill%3D'none'%20stroke%3D'black'%20stroke-width%3D'1'%2F%3E%3C%2Fsvg%3E&quot;); background-color: transparent">
<div style="background-color: red; border-radius:6px"; padding: 1px; display: block;></div>
</div>
html css frontend tailwind-css z-index
1个回答
0
投票

另一种方法可以使用 ::before 伪元素,它将以相对于父容器的绝对定位方式渲染“背景”(svg 对角线)。

这样您仍然可以使用

position: absolute
,但在 css 领域中定义的元素中,并且它将叠加在
.child
元素上。

.parent {
  position: relative;
  background-color: transparent;
}

.child {
  position: relative;
  background-color: red;
  border-radius: 6px;
  padding: 1px;
  display: block;
  
  /*crops the background taking into account the corder radius*/
  overflow: hidden; 
  
  /*here I'm giving an height otherwise since there's no content it would be zero*/
  height: 5em; 
}

.child::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20version%3D'1.1'%20preserveAspectRatio%3D'none'%20viewBox%3D'0%200%2010%2010'%3E%20%3Cpath%20d%3D'M%2010%200%20L%200%2010'%20fill%3D'none'%20stroke%3D'black'%20stroke-width%3D'1'%2F%3E%3C%2Fsvg%3E");
  background-repeat: no-repeat;
  background-size: cover;
}
<div class="parent">
  <div class="child"></div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.