When working with CSS variables, it is often desirable to use a unitless value to maintain flexibility and control over the presentation. However, CSS properties expect specific units in various situations. This guide will demonstrate a technique to use unitless variables and seamlessly convert them to the required units.
Scenario:
You need to define a variable --mywidth with a numerical value. However, within your CSS, you want to utilize this variable as both a percentage for elements' width and a plain number for calc() operations.
Solution:
calc() and Unit Multiplication:
To achieve this, employ the calc() function and perform a simple multiplication with the desired unit. For example:
div { width: calc(var(--mywidth) * 1%); }
This approach rescales the unitless variable --mywidth to a percentage value, adhering to the requirement of the width property. Similarly, to use the variable as a number for calculations, adjust the multiplier accordingly:
calc(var(--mywidth) * 1px)
Example:
Consider the following code:
: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; }
In this example, the --a variable starts off unitless. Within the .box class, calc() is used to convert it to percentages, pixels, and degrees as needed. The result is a box with the specified dimensions, border width, gradient angle, and padding.
This technique empowers you to define CSS variables with unitless values and subsequently convert them to the appropriate units, providing greater flexibility and efficiency in your CSS styling.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3