CSS Z-index changing unexpectedly
I have simplified this just to show what is going on. I have a box (originally a button), with a 3D effect. When it is hovered over, the box rises by 2 pixels and the 3D effect drops by 3 pixels (hiding it). However, for some reason the 3D effect behind the box moves in front. Can anyone explain why this is please? https://codepen.io/iBlackwolf/pen/ZEZWdQx
21 Replies
Did you try giving a z-index to #box
yes, messed about with alsorts of z-indexes and it just gets weirder
First of all. body already takes full width, so width:100vw; makes no sense. and vh should only be used as a fallback. better using svh and vh as fallback.
https://www.youtube.com/watch?v=veEqYQlfNx8
Also, you want to do this? Is this the effect you looking for?
https://codepen.io/tok124/pen/MWReaLz
Kevin Powell
YouTube
The problems with viewport units
Conquering Responsive Layouts (free course): https://courses.kevinpowell.co/conquering-responsive-layouts
Join the Discord: https://kevinpowell.co/discord
Viewport units often feel like this cheat code that makes things so much easier when you first discover them, but they actually are problematic for a number of reasons, from creating horizon...
that's better than mine, i do want the 3D effect to drop a little - the idea is to make it look like a button is pressed in and i don't want to move the foreground too much. the viewport is generic as it's just for developing components. i shall analyse your code later. thank you so much
Refresh the pen. I made it look a little better
excellent job, thank you again 🙂
i shall analyse the differences when i get some free time 🙂
... i need to understand what i actually did wrong
I see you made the box in a completely different way. I would like to understand why the z-index flips on my original when all I am doing is moving items up and down
The
transform
on hover is creating a new stacking context. I've made a little video where I explain it in more detail 🙂If you don't mind, I might chop this up a little and turn it into a YT video
I just gave the #box a z-index of 1 and it came over red box
yea, it does crazy things
You did want blue over red, right?
no
Ahh… my bad! I assumed you wanted blue over red 😅
imagine the red as a button and the blue as it's 3D - when pressed, the red gets a little higher and the blue lower, so it looks like it's being pressed
Ahh… transform is your friend then
it's transform that appears to be breaking the z-index lol
I’ll duplicate and let you know 😅
ok, thanks
The main issue is that the box and it's pseudo class are not in the same stacking order. I mean you are moving the box and its before both using transform property. If you try wrapping the box in a container div and then on hover of that div you move the before, it will work as you expect it to work.
https://codepen.io/i4mabdul/pen/BaEzRRg
transform have their own stacking order. Check out my codepen and see if that's the effect you wanted