user1454265
user1454265

Reputation: 878

CSS 3D transform independent of element size?

Is it possible to define a CSS 3D transform that does the same deformation independent of the transformed element's size? Ideally, something that would be preserved as the element is arbitrarily/fluidly resized.

I've got a simple transform with perspective and transform: rotateY. I see that as the transformed element changes size, the amount of skew changes (it appears to rotate more about the Y axis):

.perspective {
  perspective: 2000px;
}

.xform {
  transform: rotateY(45deg);
}

.xsmall {
  width: 100px;
}

.small {
  width: 200px;
}

.medium {
  width: 400px;
}

.large {
  width: 800px;
}
<div class="perspective">
  <img src="https://loremflickr.com/50/50" class="xsmall xform" />
</div>
<div class="perspective">
  <img src="https://loremflickr.com/50/50" class="small xform" />
</div>
<div class="perspective">
  <img src="https://loremflickr.com/50/50" class="medium xform" />
</div>
<div class="perspective">
  <img src="https://loremflickr.com/50/50" class="large xform" />
</div>

This makes physical sense considering what perspective means, but what I want is the same transformation for an object of any size. (My use case is superimposing a screenshot over a PNG of a rotated device frame, and keeping it responsive). Is this possible?

Upvotes: 0

Views: 452

Answers (1)

Olex Ponomarenko
Olex Ponomarenko

Reputation: 913

You can get a consistent transform effect by resizing using the scale transform to make the whole image smaller to fit your desired output.

Careful: scaling up can introduce unwanted pixelation. So just get the transformed output with rotation right on a medium-large screen and then add media queries to scale it down.

Here's your example:

.perspective {
  perspective: 2000px;
}

.xform {
  width: 100px;
  transform: rotateY(45deg);
}

.xsmall {
  transform: rotateY(45deg);
}

.small {
  margin-top: 150px;
  transform: rotateY(45deg) scale(2);
}

.medium {
  margin-top: 300px;
  transform: rotateY(45deg) scale(4);
}

.large {
  margin-top: 650px;
  transform: rotateY(45deg) scale(8);
}
<div class="perspective">
  <img src="https://loremflickr.com/50/50" class="xsmall xform" />
</div>
<div class="perspective">
  <img src="https://loremflickr.com/50/50" class="small xform" />
</div>
<div class="perspective">
  <img src="https://loremflickr.com/50/50" class="medium xform" />
</div>
<div class="perspective">
  <img src="https://loremflickr.com/50/50" class="large xform" />
</div>

Upvotes: 1

Related Questions