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;
}
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.
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%.
.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With