I need help understanding how z-index of elements is affected by nesting or not nesting elements inside eachother. I have managed to get my code working (which should have a clickable image (image which redirects user to some other page/section) which when hovered should have an overlay displayed over the image.
However when i change the html code as such the overlay is displayed differntly:(moved i move the closing tag from line 2 to line 4 the overlay isnt displayed correctly anymore and i dont understand why)
original: (part of working code, overlay displays on top of image as expected)
<div class="image">
<a href="www.google.com" class="image__link"></a>
<img class="image__img" src="https://www.slntechnologies.com/wp-content/uploads/2017/08/ef3-placeholder-image.jpg" />
after moving closing Anchor tag: (not working properly, image displays on top of overlay and overlay is not visible)
<div class="image">
<a href="www.google.com" class="image__link">
<img class="image__img" src="https://www.slntechnologies.com/wp-content/uploads/2017/08/ef3-placeholder-image.jpg" />
</a>
I did not change the CSS, did not change the z-index of the elements, only changed the location of closing anchor tag. The overlay opacity is still changed when user hovers (as can be seen when changing opacity of .image__img class to <1). But for some reason the overlay isn’t displayed above the image anymore..
Please can someone explain why this is happening?
Thank you!
Codepen 1: (overlay displays in front of image/is visible (desired result))
https://codepen.io/domipomi123/pen/ExemymY
Codepen 2: (overlay displays behind image)(changed image opacity to 0.5 to make overlay visible even when behind image)
https://codepen.io/domipomi123/pen/eYLWpLO
2
Answers
The issue is that the ruleset shown below moves the link (and it’s children) above the overlay which only has a
z-index
of 99. And, as you noticed, if you don’t have the anchor on top, it doesn’t register the hover because the mouse event is captured by the overlay on top.To fix this, I removed the absolute positioning on the anchor and I added
pointer-events: none;
to the overlay so that it wouldn’t interfere with registering when you hover on the anchor tag. As a general rule, try and keep positioned elements to a minimum. Here, the only thing you need to position is the overlay and the "grid" element that is set to relative.Another best practice is to not use ids in CSS to keep CSS specificity to a minimum level, so I removed the unnecessary ids and stuck to your BEM conventions.
Here is a quick example of a Call To Action (CTA) layout. I threw together with some ugly color and borders just to show where things are.
z-index
for the hover effect.