This is the 14th day of my participation in the August More Text Challenge
scenario
Want to use JS variables in CSS (dynamically assigning CSS properties)
The solution
CSS variable
The sample
Take the VUE project as an example:
- Define CSS variables in the inline style property
- Assign to a JS variable
- Use inline CSS variables in CSS
<! --html-->
<div class="container">
<div class="test" :style="{ '--width':width, '--color':color, '--margin':margin }"></div>
</div>
Copy the code
// js
data(){
return {
width:'200px'.color:'#f00'.margin:'10px 20px 10px 20px',}}Copy the code
.test{
width: var(--width);
color: var(--color);
margin: var(--margin);
}
Copy the code
CSS variables – Custom properties
Concepts and Features
- With a prefix
--
Property name, such as--example--name
Represents a custom attribute with a value that can be reused across the document using the var function - CSS custom properties can be cascaded: each custom property can appear multiple times, and the value of the variable will be calculated using the cascading algorithm and the custom property value
This means that the same custom attribute name can be assigned multiple times
grammar
—
:
Use of var() : developer.mozilla.org/zh-CN/docs/…
Example:
Variable scope
- CSS variables can be defined within any element
- Add CSS custom attributes to :root to make them available to all elements in the page
- If you add variables to the.container selector, they are only available in the.container (scope issue)
JS interacts with CSS variables
- Set element styles:
[el].style.setProperty ([attribute name], [value])
Get the element style:GetComputedStyle ([el])
Get the element style attribute value:[styles].getPropertyValue ([Property name])
Reference links:
- Js Set CSS custom variable _CSS variable (custom property)
- Developer.mozilla.org/zh-CN/docs/…
- Super fun new feature in Vue: JS variables in CSS