The stylus stylus uses variables for stylus design, but CSS can also define variables. Since dynamic CSS syntax is not supported in native programs, CSS variables can be used to simplify the development process.

Basic usage

Basic usage

<!--webTop-level variables in developmentkeyName is the:root, small program usepage-->
page { 
  --main-bg-color: brown;
}

.one {
  color: white;
  background-color: var(--main-bg-color);
  margin: 10px;
}

.two {
  color: white;
  background-color: black;
  margin: 10px;
}
.three {
  color: white;
  background-color: var(--main-bg-color);
}
Copy the code

Promote usage

<div class="one">
  <div class="two">
    <div class="three">
    </div>
    <div class="four">
    </div>
  <div>
</div>
Copy the code
.two { --test: 10px; }
.three { --test: 2em; }
Copy the code

In this example, var(–test) results in:

Class =”two” class=”three” class=”three” class: element: 2em class=”four” class: 10px (inherited from parent. Two) class=”one” class: Invalid value, that is, the property value is a default value that is not overridden by a custom CSS variable

These are some basic concepts that outline how CSS variables are used. Note that in Web development, we use root to set top-level variables. Refer to the MDN documentation for more details

Use CSS variables wisely

A common problem in development is that CSS data is written dead and cannot be directly connected to JS variables, that is, some data is dynamically changed, but CSS cannot use it. By the way, try using CSS variables

wxml

js

// Set CSS variables in js
let myStyle = ` --bg-color:red; --border-radius:50%; --wid:200px; --hgt:200px; `

let chageStyle = ` --bg-color:red; --border-radius:50%; --wid:300px; --hgt:300px; `
Page({
  data: {
    viewData: {
      style: myStyle
    }
  },
  onLoad(){
    setTimeout((a)= > {
      this.setData({'viewData.style': chageStyle})
    }, 2000); }})Copy the code

wxml

<! -- assign CSS variables (set in js) to style-->
<view class="container">
  <view class="my-view" style="{{viewData.style}}">
    <image src="/images/abc.png" mode="widthFix"/>
  </view>
</view>
Copy the code

wxss

Var */
.my-view{
  width: var(--wid);
  height: var(--hgt);
  border-radius: var(--border-radius);
  padding: 10px;
  box-sizing: border-box;
  background-color: var(--bg-color);
  transition: all 0.3 s ease-in;
}

.my-view image{
  width: 100%;
  height: 100%;
  border-radius: var(--border-radius);
}
Copy the code

CSS variables are used to dynamically set CSS property values

Code snippet

Developers.weixin.qq.com/s/aWfUGCmG7…

github

The following small program DEMO containsDrop-down menu, general filter list, index list, Markdown (including table), scoring component, fruit slot machine, folding panel, two-column category navigation (left and right), scratch card, calendarComponents such as