Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center div on screen that has been rotated and scaled with css3

Tags:

html

css

I have the following jsfiddle:

https://jsfiddle.net/quacu0hv/

I cant figure out how to center this div. The fact that it is rotated makes it hard to actually center the object on screen. How exactly can this be achieved with pure css? I imagine its due to the point of origin that changed its position (upper left vertex of the div).

div {
  transform: rotate(-45deg) scale(2) translate(-50%, -50%);
  opacity: 1 !important;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  background: black;
  position: absolute;
}
like image 846
Asperger Avatar asked Aug 26 '16 17:08

Asperger


2 Answers

Try rearranging the transform values and see what happens ;)

Turns out order does matter. If you think about it, it does makes sense:

Rotate > Scale > Translate

Once you've rotated it, the origin has been rotated too. That's why your square moves "left" and "up" from the origin.


Translate > Rotate > Scale

This is what you want to do. Position before you make any other adjustments that can affect the origin.

like image 101
Luke Fixt Avatar answered Oct 19 '22 23:10

Luke Fixt


Use CSS transform-origin: 50% 50% or try 0 0. Remove position: absolute first.

This is at 0 0

This is at 50% 50%

This is at 45% -290% Centered?

Yeah, looks centered to me, see Full Page. Anyways, as you can see from the other answers transform-origin is the best solution. Scott suggested to remove the transform: -50% -50% which makes perfect sense if you wanted the div centered in the first place, but if you wanted that in there still and have it centered as a square in a rectangle (height is smaller than width), then 45% by -290%.

SNIPPET

.box {
  position: relative;
}
.center {
  transform: rotate(-45deg) scale(2) translate(-50%, -50%);
  transform-origin: 45% -290%;
  opacity: 1 !important;
  width: 200px;
  height: 200px;
  background: black;
  position: absolute;
}
<div class='box'>
  <div class='center'></div>
</div>
like image 26
zer00ne Avatar answered Oct 19 '22 23:10

zer00ne