Home > Web Front-end > CSS Tutorial > Can CSS Variables Be Dynamically Used with Different Units?

Can CSS Variables Be Dynamically Used with Different Units?

Linda Hamilton
Release: 2024-11-17 19:38:02
Original
616 people have browsed it

Can CSS Variables Be Dynamically Used with Different Units?

Unitless CSS Variables with Dynamic Units

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%
Copy after login

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%);}
Copy after login

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;
}
Copy after login
<div class="box"></div>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template