The cos()
function can be used to keep the size of a rotated box.
When the element is rotated using rotate()
, it goes beyond its initial size. To fix this, we will use cos()
to update the element size.
For example, if you rotate a 100px
/100px
square 45deg
, the diamond it creates will be wider and taller than the original square. To shrink the diamond into the box allotted for the original square, you would have to scale down the diamond using this formula: width = height = 100px * cos(45deg) = 100px * 0.707 = 70.7px
. You need to also adjust the transform-origin
and add translate()
to correct the position:
HTML
<div class="original-square"></div>
<div class="rotated-diamond"></div>
<div class="rotated-scaled-diamond"></div>
CSS
div.original-square {
width: 100px;
height: 100px;
background-color: blue;
}
div.rotated-diamond {
width: 100px;
height: 100px;
background-color: red;
transform: rotate(45deg);
}
div.rotated-scaled-diamond {
width: calc(100px * cos(45deg));
height: calc(100px * cos(45deg));
margin: calc(100px / 4 * cos(45deg));
transform: rotate(45deg);
transform-origin: center;
background-color: green;
}
Result