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>
2
Answers
Another approach could be using a
::before
pseudo element that will render the "background" (the svg diagonal line) in a absolute positioned manner relative to its parent container.child
.This way you can still use
position: absolute
but in an element defined in the css realm and that will superimpose over the.child
element.Since the
.parent
div is not needed anymore, I decided to remove it and show how you can apply that strategy to a single div having its own background (red) that you wish to overlay with your svg.You can use ::after to style your parent element with position absolute so it does not break your layout