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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hmmmmmmm</title>
<style>
body {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#box {
position: relative;
width: 150px;
height: 150px;
border: none;
border-radius: 30px;
background-color: #f00;
font-size: 20px;
color: #fff;
cursor: pointer;
}
#box::before {
position: absolute;
content: '';
width: 146px;
height: 150px;
left: 2px;
top: -5px;
border: none;
border-radius: 30px;
background-color: #44f;
z-index: -1;
}
#box:hover {
transform: translateY(-2px);
}
#box:hover::before {
transform: translateY(3px);
}
</style>
</head>
<body>
<div id="box"></div>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hmmmmmmm</title>
<style>
body {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#box {
position: relative;
width: 150px;
height: 150px;
border: none;
border-radius: 30px;
background-color: #f00;
font-size: 20px;
color: #fff;
cursor: pointer;
}
#box::before {
position: absolute;
content: '';
width: 146px;
height: 150px;
left: 2px;
top: -5px;
border: none;
border-radius: 30px;
background-color: #44f;
z-index: -1;
}
#box:hover {
transform: translateY(-2px);
}
#box:hover::before {
transform: translateY(3px);
}
</style>
</head>
<body>
<div id="box"></div>
</body>
</html>
