markasoftware
markasoftware

Reputation: 12652

TranslateZ Percentages CSS 3D Transforms

When I try to set percentages in translateZ like this:

transform:translateZ(-100%);

it doesn't work. It also doesn't work with viewport relative vh or vw. Is there some way to do this? I understand that I can simply set it with JavaScript, but I have many of these elements in a certain class, including ones that are added later dynamically with JavaScript. It would be much more convenient to do something in CSS. I saw something which seemed like a duplicate, but I would like a way that doesn't have to have multiple elements to fix it. Apart from appending to the <style> element, that is

Upvotes: 9

Views: 3947

Answers (2)

Tanush J
Tanush J

Reputation: 1

The only reason I can think of for the percentage not working translateZ is that there is no thickness to elements in general. So they can't move in the z-axis unless you use absolute units.

I created a cube in codepen it might clear something

<div class="cube">
  <div class="face one"></div> <!-- blue -->
  <div class="face two"></div> <!-- purple -->
  <div class="face three"></div> <!-- green -->
  <div class="face four"></div> <!-- yellow -->
  <div class="face five"></div> <!-- gray -->
  <div class="face six"></div> <!-- orange -->
</div>
.cube {
  height: 200px;
  width: 200px;
  position: relative;
  margin: 100px;
  transform-style: preserve-3d;
  perspective: 2000px;
  transform: rotateX(25deg) rotateY(25deg);
  outline: 1px solid black;
}
.face {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 20%;
  left: 20%;
  transition: all 1s;
}

.one {
  background-color: blue;
  transform: translateZ(100px)
}

.one:hover {
  transform: rotateX(40deg) rotateY(40deg);
}

.two {
  background-color: purple;
  transform: translateX(-50%) rotateY(90deg);
}

.three {
  background-color: green;
  transform: translateZ(-100px);
}

.four {
  background-color: yellow;
  transform: translateX(50%) rotateY(90deg) ;
}

.five {
  background-color: gray;
  transform: translateY(-50%) rotateX(90deg);
}

.six {
  background-color: orange;
  transform: translateY(50%) rotateX(90deg);
}

Upvotes: 0

vals
vals

Reputation: 64164

Well, reading the w3c specification for translateZ, it's not clear that anybody has think about what should do a percentage value there ..(or at least, it's not clear for me what should be the implementation).

What has been decided in the standard, however, is that translateX(100%) will be relative to width.

So, a way to get what you want would be to rotate until the x axis is in the z axis, do a x translation, and restore the rotation:

CSS

transform: rotateY(-90deg) translateX(100%) rotateY(90deg);

In this demo you can see that the test element, that has that transform applied, gets to the same position that the ref element , that has a translateZ(100px) applied (since the element width is 100px)

Upvotes: 16

Related Questions