Skip to main content
CSS Tip

Remove the unit from any CSS value

Do you want to convert a length value to a unitless value? It's possible with a simple CSS trick.

/* register the value as a length */
@property --val {
syntax: '<length>';
inherits: true;
initial-value: 0;
}

:root {
--val: 25em; /* use any length unit (px, em, ex, ch, rem, ...)*/

/* divide it by 1px and you get a uniteless value */
--unitless-val: calc(var(--val)/1px);
/* for better support you can do the below
--unitless-val: tan(atan2(var(--val),1px));
*/

}
/* As a bonus, you can also show the unitless value */
body:before {
content: counter(c);
counter-reset: c var(--unitless-val);
}

See the Pen Remove the unit from any CSS value! by Temani Afif (@t_afif) on CodePen.

The same trick works with other types as well. Example with angle:

/* register the value as an angle */
@property --val {
syntax: '<angle>';
inherits: true;
initial-value: 0;
}

:root {
--val: 90deg;
--unitless-val: calc(var(--val)/1deg);
/* for better support you can do the below
--unitless-val: tan(atan2(var(--val),1deg));
*/

}

More CSS Tips