JSFiddle - React, Tailwind, and code Playground

by tonytlwu

HTML

<div class="card-container">
  <div class="card">
    <div class="front">
      <h2>Front</h2>
      <p>This is the front of the card.</p>
    </div>
    <div class="back">
      <h2>Back</h2>
      <p>This is the back of the card.</p>
    </div>
  </div>
</div>

CSS

.card-container {
  perspective: 1000px;
  /* Set the perspective for the 3D effect */
}

.card {
  position: relative;
  width: 300px;
  height: 200px;
  transition: transform 0.5s;
  transform-style: preserve-3d;
}

.front,
.back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

.front {
  background-color: #eee;
}

.back {
  background-color: #ccc;
  transform: rotateY(180deg);
}

/* Add the tilt effect */
.card:hover {
  transform: rotateX(var(--tilt-x)) rotateY(var(--tilt-y));
}

/* Define the tilt angle variables */
:root {
  --tilt-x: 0deg;
  --tilt-y: 0deg;
}

JavaScript

const card = document.querySelector('.card');
const container = document.querySelector('.card-container');

container.addEventListener('mousemove', e => {
  // Calculate the tilt angles based on the mouse position
  const xAngle = (e.clientX / window.innerWidth) * 60 - 30;
  const yAngle = (e.clientY / window.innerHeight) * 60 - 30;
  
  // Update the CSS variables to apply the tilt effect
  card.style.setProperty('--tilt-x', `${xAngle}deg`);
  card.style.setProperty('--tilt-y', `${yAngle}deg`);
});