Z-index problem in setting the background

Hello everyone! I am working on a small assignment based on HTML/CSS which involves coding a information card. Here is the link to the codepen: https://codepen.io/anurag1989/pen/bGOybYr Now, the main problem is: (1) When img::before has been assigned z-index: -1, then it is sent behind .card (as per docs, any element with negative z-index in sent behind its parent. But, here, .img is the immediate parent container so why ::before is sent behind .card and not behind .img?) (2) When img::before has been assigned z-index: -1 and .card z-index: 1, then the ::before is sent behind .img and above .content (3) When img::before has been assigned z-index: -1, .card z-index: 1 (optional) and .img z-index: 1, then ::before is sent behind img but above .img. In this way there are other combinations of z-indexes for this scenario which is proving difficult for me. Can somebody explain me what exactly is happening here?
3 Replies
Jus Sus || 💀
Jus Sus || 💀14mo ago
@Anurag Gupta To answer your first question, When you assign a z-index to an element, it creates a new stacking context. Any child elements (including pseudo-elements like ::before) become part of this stacking context. The z-index values of child elements are then relative to this context, not the entire page1. So, when you give the::before pseudo-element a z-index of -1, it’s sent behind its parent.img within the stacking context of .img. But since .img doesn’t have a z-index defined and is not a root element, the stacking context falls back to the next parent .card that forms a stacking context1. @Anurag Gupta .card (z-index: 1): This element is given a z-index of 1, which means it will be rendered in front of any elements with a lower z-index. Since .card is the parent of .img, it forms a new stacking context for its children. .img (no z-index specified): This element doesn’t have a z-index specified, so it’s rendered within the stacking context of its parent, which is .card. It will be rendered behind any siblings with a higher z-index. img::before (z-index: -1): This pseudo-element is given a z-index of -1, which means it will be rendered behind its parent, .img, within the stacking context of .img. However, since .img is within the stacking context of .card, img::before will still be rendered above any content in .card that doesn’t have a higher z-index.
Anurag Gupta
Anurag GuptaOP14mo ago
Can you shed some more light on 'Stacking Content' and how it is formed? I think I am getting confused here.
capt_uhu
capt_uhu14mo ago
this is the article that finally made z-index make sense to me: https://coder-coder.com/z-index-isnt-working/
Want results from more Discord servers?
Add your server