CSS variables realize dynamic change of theme color

insert image description here

Recently, I thought about how to realize the theme color switching of the website. The solution is to use css variables. Nowadays, css variables are used more and more frequently in the process of website development, and Element plus also uses css variables to reconstruct the style system of almost all components. CSS variables are a very useful feature, supported by almost all browsers.

This article will talk about the use of css variables.

css variables in global scope

A general best practice is to define it under the root pseudo-class :root so that it can be accessed from anywhere in the HTML document:

:root {
    
    
  --main-bg-color: brown;
}

<!-- 在需要的元素中使用 -->
element {
    
    
  background-color: var(--main-bg-color);
}

After defining a series of variables in this way, it means that they can be dynamically modified. The following is to control css variables through js, you can do this:

// 获取全局 css 变量
getComputedStyle(document.documentElement).getPropertyValue(`--main-bg-color`)

// 设置 css 变量
document.documentElement.style.setProperty('--main-bg-color', 'red')

Use css variables locally

.div200 {
    
    
  --main-bg-color: #000;
  height: 100px;
  background-color: var(--main-bg-color);
  margin-top: 20px;
}

If you want to control the css variable of an element through js, you can do this:

// 获取某个标签上的css变量
getComputedStyle(document.querySelector('.div200')).getPropertyValue('--main-bg-color')

// 设置 css 变量
document.querySelector('.div200').style.setProperty('--main-bg-color', '#fff')

With these conditions, dynamic switching of website themes is probably the way of thinking.

If you are using the vue3 technology stack, there is a more elegant way to manipulate css variables, useCssVar | VueUse .

The article was first published on my blog - "css variable realizes dynamic change of theme color"

Guess you like

Origin blog.csdn.net/IICOOM/article/details/130348471