I have a parent div
which has a background image (an SVG with just a diagonal line).
My child div
will have some background-color depending on the value of a variable.
I want to show the parent background image (diagonal line) over my child div
background colour.
Naturally, I resorted to using z-index. But it doesn't work. Setting z-index : -1
for child div
hides it altogether (I think that happens because it is going behind the root div itself).
My limitation is I cannot position both the parent or child divs as absolute
, otherwise my layout would go for a toss (positioning them as relative for z-index to take effect)
<div style="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-color: transparent">
<div style="background-color: red; border-radius:6px"; padding: 1px; display: block;></div>
</div>
You can use ::after to style your parent element with position absolute so it does not break your layout
.parent {
position: relative;
background-color: transparent;
}
.parent::after {
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-size: cover;
/* Adjust as necessary */
z-index: 1;
/* z-index 1 to make sure it overlays the child */
}
.child {
border-radius: 6px;
padding: 1px;
display: block;
position: relative;
background-color: red;
z-index: 0;
}
<div class="parent">
Parent
<div class="child">child</div>
</div>