Jijisasu Nijimura
Jijisasu Nijimura

Reputation: 21

How to use CSS translateZ?

I'm trying to make a different layer of content in CSS but translateZ doesn't seem to modify the depth of the element. I used some codepen code to make the 3d effect.

Here is the HTML, CSS and Javascript code.

let card = document.querySelector('.card');

document.addEventListener('mousemove', function(e) {
  let xAxis = (window.innerWidth / 2 - e.pageX) / 10;
  let yAxis = (window.innerHeight / 2 - e.pageY) / 5;
  card.style.transform = `rotateY(${xAxis}deg) rotateX(${yAxis}deg)`;
});
.area {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
    height: 100%;
    
    transform-style: preserve-3d;
    perspective: 1000px;
}
.card {
    margin: auto;
    justify-content: center;
    display: flex;
    flex-direction: column;
    width: 500px;
    height: 500px;
    background-color: red;

    transform-style: preserve-3d;
    transform: translateZ(50px); //not working
}
.card-content {
    margin: auto;
    width: 400px;
    height: 400px;
    background-color: blue;

    transform-style: preserve-3d;
    transform: translateZ(100px); //not working
}
<header id = "header" class = "NC17">
    <div class = "area">
        <div class = "card">
            <div class = "card-content"></div>
        </div>
    </div>
</header>

Upvotes: 2

Views: 360

Answers (1)

M-Coder
M-Coder

Reputation: 70

When your JS executes, it is changing your transform property from "translateZ" to "rotateY and rotateX". If you want to keep the translateZ attribute, your JS should look like this:

let card = document.querySelector('.card');

document.addEventListener('mousemove', function(e) {
  let xAxis = (window.innerWidth / 2 - e.pageX) / 10;
  let yAxis = (window.innerHeight / 2 - e.pageY) / 5;
  card.style.transform = `rotateY(${xAxis}deg) rotateX(${yAxis}deg) translateZ(50px)`;
});

Upvotes: 1

Related Questions