I’m trying to achieve a layout where I have a div with position: relative, and inside it, I want to place another div with position: absolute. However, I want only the part of the absolute div that is outside the relative div to be visible, while the part inside the relative div should be hidden. How can I accomplish this effect using CSS? Any help would be appreciated!
.relative-container {
position: relative;
width: 200px;
height: 200px;
background-color: red;
z-index: 2;
}
.absolute-element {
position: absolute;
bottom: -10px;
right: -10px;
z-index: 1;
width: 100px;
height: 100px;
background-color: blue;
}
<div class="relative-container">
<div class="absolute-element"></div>
</div>
4
Answers
Just remove
z-index
declaration from the relative container and put a negativez-index
to the absolute container.You could for instance just put the absolute-element behind the relative div like you tried with z-index but the relative div itself can’t have z-index otherwise it becomes the z-index ancestor of the absolute div and can’t be put behind anymore
If you need the red div to have z-index then you can root both to another (possibly invisible) parent div and set them both to absolute.
You can use
mix-blend-mode
:Or 3D transform: (Credit: How to get a child element to show behind (lower z-index) than its parent?)
The other provided solutions won’t work if you create a stacking context in the parent (see CSS negative z-index: what does it mean?):