project demo
html code
CSS Card 3D Tilt Effect | Dark CSS
css code
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #c9ffe2;
background: linear-gradient(90deg, rgba(201, 255, 226, 1) 50%, rgba(255, 245, 158, 1) 100%);
}
/* Styles for the tilt block */
#tilt {
display: block;
height: 200px;
width: 300px;
background-color: grey;
margin: 0 auto;
border-radius: 12px;
transition: box-shadow 0.1s, transform 0.1s;
background-image: url(images/image.jpg);
background-size: 100%;
background-repeat: no-repeat;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.25);
}
#tilt:hover {
box-shadow: 0px 0px 30px rgba(0, 0, 0, 0.25);
cursor: pointer;
}
javascript code
let el = document.getElementById("tilt");
const height = el.clientHeight;
const width = el.clientWidth;
el.addEventListener("mousemove", handleMove);
function handleMove(e) {
const xVal = e.layerX;
const yVal = e.layerY;
const yRotation = 20 * ((xVal - width / 2) / width);
const xRotation = -20 * ((yVal - height / 2) / height);
const string =
"perspective(500px) scale(1.1) rotateX(" +
xRotation +
"deg) rotateY(" +
yRotation +
"deg)";
el.style.transform = string;
}
el.addEventListener("mouseout", function () {
el.style.transform = "perspective(500px) scale(1) rotateX(0) rotateY(0)";
});
el.addEventListener("mousedown", function () {
el.style.transform = "perspective(500px) scale(0.9) rotateX(0) rotateY(0)";
});
el.addEventListener("mouseup", function () {
el.style.transform = "perspective(500px) scale(1.1) rotateX(0) rotateY(0)";
});