Use calc() in transform:rotate()

11.1k views Asked by At

How to use calc() to determine the angle value for transform:rotate()?

The !mdn docs for the CSS calc() function states:

The calc() CSS function can be used anywhere a <length>, <frequency>, <angle>, <time>, <number>, or <integer> is required. With calc(), you can perform calculations to determine CSS property values.

However, using calc() to create an angle value for transform:rotate() isn't working for me.

The suggestion of this blog doesn't work -- transform: rotate(calc(1turn - 32deg));, nor similar variants of operations using calc() in this way.

See this codepen for verification - only the fifth <div> rotates as expected and doesn't use calc() to determine the angle.

Here is the main code from the codepen to show here:

div {
  height: 200px;
  width: 200px;
  background-color: red;
}

.one {
  transform: rotate(calc(1turn - 32deg));
}

.two {
  transform: rotate(calc(360deg - 90deg));
}

.three {
  transform: rotate(calc(360deg/4deg));
}

.four {
  transform: rotate(calc(22deg + 23deg));
}

.five {
  transform: rotate(45deg);
}

This same problem happens for me across the latest Chrome, Firefox Developer Edition, and Safari.

Other discussions related to this problem exist, but don't offer any solution. For example:

2

There are 2 answers

1
Mifort On BEST ANSWER

Spaces matter in calc()

CORRECT:

.three {
    transform: rotate(calc(360deg / 4));
}

INCORRECT:

.three {
    transform: rotate(calc(360deg/4deg));
}

Because 360deg / 4deg == 90 and 360deg / 4 = 90deg. And you are looking for a degrees and not a pure number.

0
The One and Only ChemistryBlob On

I have also encountered the same problem and have also tried the calc() function inside other angular transform functions such as skewX and skewY on both Chrome (v59.0) and FF(v54.0). In both cases the skew function did not skew as expected.

Note that calc() functions used for the family of length-based translate() transform functions does work (see this Fiddle).

The z-direction of translate3D() is not working in my Fiddle but you can see how it works using the Codepen link on this page

Notice how skewX() works properly for #div1 as a hard-coded angle but if you re-write this using calc() as an argument (e.g., try calc(-45deg + 1rad) ), it breaks the css for #div1.