This is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hovering Boxes</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container"></div>
<script>
let container = document.getElementById('container');
let boxCount = 100;
for(let i = 0; i < boxCount; i++) {
let box = document.createElement('div');
box.className = 'box';
container.appendChild(box);
}
</script>
</body>
</html>
And this is my CSS:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#container {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
gap: 5px;
width: 100%;
perspective: 1000px;
}
.box {
background-color: red;
height: 50px;
width: 50px;
transform-style: preserve-3d;
transition: transform 0.5s, filter 0.3s;
}
.box:hover {
transform: translateZ(150px);
filter: brightness(1);
background-color: #87F1FF;
}
.box:hover + * {
transform: translateZ(100px) rotateY(60deg);
filter: brightness(0.8);
}
.box:hover + * + * {
transform: translateZ(50px) rotateY(30deg);
filter: brightness(0.6);
}
.box:hover + * + * + * {
transform: translateZ(25px) rotateY(15deg);
filter: brightness(0.4);
}
.box:has(+ *:hover) {
transform: translateZ(100px) rotateY(-60deg);
filter: brightness(0.8);
}
.box:has(+ * + *:hover) {
transform: translateZ(50px) rotateY(-30deg);
filter: brightness(0.6);
}
.box:has(+ * + * + *:hover) {
transform: translateZ(25px) rotateY(-15deg);
filter: brightness(0.4);
}
This code currently selects the hovered element and sets effects to its following and preceding elements. However, I also want the top and bottom elements relative to the hovered element to receive similar effects.
What would be the best approach to select and style these top and bottom elements when hovering over a box?
I have tried using JavaScript to achieve this but couldn’t find an effective solution. Any help or guidance would be greatly appreciated!
2
Answers