Manipulating CSS variables can often present challenges when using both percentage-based and unitless values. This question explores how to assign a unitless CSS variable and then use it interchangeably with various units.
Question:
Can a CSS variable be set with a number and then used as a percentage in one instance and a plain number in another? For example:
--mywidth:10; div{width:var(--mywidth) + %;} --- should be ---> width:10%
Answer:
Yes, it is possible to achieve this using the calc() function. By multiplying the variable by an appropriate unit, we can convert it to any desired unit dynamically.
To use the variable --mywidth as a percentage, we can multiply it by 1%:
div{width:calc(var(--mywidth) * 1%);}
Example:
The following code demonstrates the use of the calc() function to dynamically add units to a unitless CSS variable:
:root { --a:50; } .box { width:calc(var(--a) * 1%); border:calc(var(--a) * 0.5px) solid red; background:linear-gradient(calc(var(--a) * 0.8deg),blue 50% ,green 0); padding:20px; box-sizing:border-box; }
<div class="box"></div>
The above is the detailed content of Can CSS Variables Be Dynamically Used with Different Units?. For more information, please follow other related articles on the PHP Chinese website!