Search code examples
htmlcssrotationtransform

Make child element unaffected by rotation of parent element


I have two div elements: one parent element, which is rotated, and one child element that I need to be unaffected by the rotation of the parent element.

To achieve this, I have attempted to rotate the child element in the opposite direction of the parent element. This works in some cases. For instance, if I rotate the elements like this ...

.parent {
  transform: rotate(30deg);
}

.child {
 transform: rotate(-30deg);
}

... the child element will appear straight and undistorted. But if I rotate them with rotateX ...

.parent {
  transform: rotateX(30deg);
}

.child {
 transform: rotateX(-30deg);
}

... the child element still looks rather distorted.

The actual code uses both rotateX and rotateZ in order to make the parent element appear isometric. It currently looks like this:

.happy_parent {
  width: 100px;
  height: 100px;
  background-color: green;
  transform: rotate(30deg);
}

.happy_child {
  width: 50px;
  height: 50px;
  background-color: yellow;
  transform: rotate(-30deg);
}

.sad_parent {
  width: 100px;
  height: 100px;
  background-color: green;
  transform: rotateX(-60deg) rotateZ(45deg);
}

.sad_child {
  width: 50px;
  height: 50px;
  background-color: yellow;
  transform: rotateX(60deg) rotateZ(45deg);
}
<div class="happy_parent">
  <div class="happy_child"></div>
</div>

<div class="sad_parent">
  <div class="sad_child"></div>
</div>

Notice that the upper divs are both rendered correctly, but the lower child-div is still distorted.

What am I missing here?


Solution

  • It is not possible to have the innerElement (childElement) to remain in initial state when rotated in 3D by rotating back in -ve deg.

    It will work when rotation takes place in 2D .

    But you can give a try to transform-style: preserve-3d to see the shapes in 3D effect when rotated with Z coordinate also and preserve the shape instead of just showing in 2D .

    You have to reverse the order of rotation too in 3D rotation

    You can try to remove the transform-style: preserve-3d and see the effect

    .happy_parent {
      width: 100px;
      height: 100px;
      background-color: green;
      transform: rotate(30deg);
    }
    
    .happy_child {
      width: 50px;
      height: 50px;
      background-color: yellow;
      transform: rotate(-30deg);
    
    }
    
    .sad_parent {
      width: 100px;
      height: 100px;
      background-color: green;
      transform: rotateX(-60deg) rotateZ(45deg);
      transform-style: preserve-3d;
    }
    
    .sad_child {
      width: 50px;
      height: 50px;
      background-color: yellow;
      transform: rotateZ(-45deg) rotateX(60deg);
    }
    <div class="happy_parent">
      <div class="happy_child"></div>
    </div>
    <br><br><br><br>
    
    <div class="sad_parent">
      <div class="sad_child"></div>
    </div>