Search code examples
htmlcsscss-transformscss-variablescss-calc

Multiplying rem units by a value to output deg units


:root {
  --length: 10rem;
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
}
hr {
  border-style: none;
  border-radius: calc( var( --length ) / 5 ); /*dividing by a unitless number works*/
  width: var( --length );
  height: var( --length );
  background-color: #444;
}

/* issue in question below */
hr {
  transform: rotate( 
    calc( 
      var( --length ) * 4.5deg 
    ) 
  );
}
<hr>

Multiplying var( --length ) which equals 10rem by 4.5 to get 45 is the desired result of the calc() function. The primary problem is getting the result of the calc() function to register in degrees.

Essentially I'm multiplying 10rem by 4.5deg with a desired output of 45deg.

Attempts have been made using a unitless value for 4.5 instead of 4.5deg and tacking on deg at the end of or after the calc() function. This did not work.

This question is primarily academic in that it has to do with the limits of vanilla CSS itself. Answers involving preprocessors such as SASS are beyond the scope.


Solution

  • Use unitless value for the length instead then you can put back the rem unit easily for the other values

    :root {
      --length: 10;
    }
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    html, body {
      height: 100%;
    }
    body {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    hr {
      border-style: none;
      border-radius: calc( var( --length ) * 1rem / 5 );
      width: calc(var( --length ) * 1rem);
      height: calc(var( --length ) * 1rem);
      background-color: #444;
    }
    
    /* issue in question below */
    hr {
      transform: rotate( 
        calc( 
          var( --length ) * 4.5deg 
        ) 
      );
    }
    <hr>