JohnT
JohnT

Reputation: 55

tranform:translateZ(0) animation explanation

I don't understand why I need a transform:translateZ(0) for this animation to work? If I remove z-index:-1 it will only swipe to the right, but have no text. If I add content:"Swipe to the right" the text will come out with the swipe, but does not create the same effect. It almost seems like transform:translateZ(0) acts as a layer mask?

div {
  display: inline-block;
  position: relative;
  margin: 0.4em;
  padding: 1em;
  cursor: pointer;
  background: #e1e1e1;
  color: white;
  transform: translateZ(0);
}
div:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #2098d1;
  transform: scaleX(0);
  transform-origin: 0 50%;
  transition: transform .3s ease-out;
}
div:hover:before {
  transform: scaleX(1);
}
<div>Sweep to the right</div>

Upvotes: 3

Views: 5161

Answers (2)

Eisa
Eisa

Reputation: 374

A value of preserve-3d for transform-style establishes a stacking context.

transform-style: preserve-3d;

Source

Upvotes: 1

JohnT
JohnT

Reputation: 55

I figured it out! Correct me if I’m wrong!

The secret lies behind the negative z-index ! It doesn’t work unless there’s a z-index of -1 on the absolute positioned div.

Even though green layer has a z-index of 1, the purple layer with the z-index of -1 overlays the green. So the stacking order looks like this

Purple (z-index: -1)

Green (z-index: 1)

That’s weird? -1 is not larger than 1 so why does this happen? Well if you change the green layer to have a z-index of 0 the stacking order looks like this

Green (z-index: 1)

Purple (z-index: 0)

This makes a lot more sense! So why does a z-index: -1 overlap the z-index:0 ? And why does the text from the z-index: 1 still show?

Here’s the explanation: Everything in the green layer has a z-index:1, BUT a negative z-index will overlap any background because a negative z-index is the 2nd lowest index! The z-index of “background” is the lowest! Here’s a photo to illustrate the z-index order

enter image description here

Hope this clears everything up!

Upvotes: 1

Related Questions