0

How to prevent children from inheriting 3d transformation CSS3?

I have a parent div and a child div, now I want to let parent using 3d transformation and the child div keep front.

Example:

.parent {
  transform: rotateX(33deg) rotateY(66deg) rotateZ(99deg);

  position: relative;
  width: 300px;
  height: 300px;
  margin: 50px auto;
  border: 4px solid darkblue;
}

.child {
  position: absolute;
  width: 80px;
  height: 80px;
  background: aqua;
}
<div class="parent">
  <div class="child">
    I'am a child want keep front.
  </div>
</div>

Set contrarotation, or set none transform is no effect.

.parent {
  transform: rotateX(33deg) rotateY(66deg) rotateZ(99deg);

  position: relative;
  width: 300px;
  height: 300px;
  margin: 50px auto;
  border: 4px solid darkblue;
}

.child {
  transform: rotateX(-33deg) rotateY(-66deg) rotateZ(-99deg);

  position: absolute;
  width: 80px;
  height: 80px;
  background: aqua;
}
<div class="parent">
  <div class="child">
    I'am a child want keep front.
  </div>
</div>
feng zhang
  • 1,193
  • 7
  • 8

1 Answers1

0

First you should make the children of the parent positioned in the 3D-space by set transform-style: preserve-3d; in parent, then you can apply transform-functions in reverse order of parent to children elements that want to keep front.

.parent {
  transform: rotateX(33deg) rotateY(66deg) rotateZ(99deg);
  /* Notice! You should make the children of the parent positioned in the 3D-space. */
  transform-style: preserve-3d;

  position: relative;
  width: 300px;
  height: 300px;
  margin: 50px auto;
  border: 4px solid darkblue;
}

.child {
  /* Notice! You should apply the opposite order of rotations (transform functions) from the parent element. */
  transform: rotateZ(-99deg) rotateY(-66deg) rotateX(-33deg);
  position: absolute;
  width: 80px;
  height: 80px;
  background: aqua;
}
<div class="parent">
  <div class="child">
    I'am a child want keep front.
  </div>
</div>

TL;DR

Why we should use reverse order?

According to transform-function - CSS: Cascading Style Sheets | MDN :

Transform-functions using matrix multiplication combin in order from right to left, and matrix multiplication doesn't satisfy the commutative law, so we should use reverse order to counteract parent's transforms.

Example:

let rotateX(33deg) = matrixA, rotateY(66deg) = matrixB, rotateZ(99deg) = matrixC

We can get rotateX(-33deg) = matrixA^-1, rotateY(-66deg) = matrixB^-1, rotateZ(-99deg) = matrixC^-1 (See: Invertible matrix - Wikipedia, Rotation matrix - Wikipedia)

We can calculate the points, rotate with parent, of children rotatedPoint = originPoint * matrixA * matrixB * matrixC.

We want to make those points in its origin position, so we should do resultPoint = rotatedPoint * matrixC^-1 * matrixB^-1 * matrixA^-1 because matrix multiplication doesn't satisfy the commutative law.

feng zhang
  • 1,193
  • 7
  • 8