Remove the unit from any CSS value
Do you want to convert a length value to a unitless value?
It's possible to remove the unit from any CSS value to get an integer!
⚠️ A hacky experimentation to use with caution ⚠️
@property --unitless-val {
syntax: '<integer>';
inherits: true;
initial-value: 0;
}
@property --_u {
syntax: '<length>';
inherits: true;
initial-value: 0;
}
:root {
--val: 25em; /* use any length unit (px, em, ex, ch, rem, ...)*/
/* we multiply then divide with the biggest value to get one unit */
--_m: 3.35544e07; /* this value depend on the browser */
--_u: calc(var(--val)*var(--_m));
--unit: calc(var(--_u)/var(--_m)); /* = 1em */
--unitless-val: tan(atan2(var(--val),var(--unit))); /* = 25 */
/* In the near future we can do
--unitless-val: calc(var(--val)/var(--unit));
*/
}
/* we need a different value for firefox */
@supports (-moz-appearance: none) {
:root {
--_m: 3.40282e38;
}
}
You may think we can use infinity
as the biggest value but it won't work because dividing by infinity will always result in 0.
Tested on Firefox, Chrome and Edge. On Firefox, it works only with px
because the value is converted to px
inside the --_u
variable.
See the Pen Remove the unit from any CSS value! by Temani Afif (@t_afif) on CodePen.
More CSS Tips
- The Filling CSS loaders Collection 20 CSS-only single element loaders.
- Default behavior of position absolute Know the meaning of initial containing block and its relation with position absolute.
- Progress element with a tooltip Adding a tooltip to the native progress element showing the precentage of progress.
- Curved avatar header with hover effect Create a fancy curved header with a cool hover effect.