[CSS] Variable usage (and use in js)

Article Directory

CSS variables can access the DOM, which means you can create variables with local or global scope, modify variables using JavaScript, and modify variables based on media queries.
A great way to use CSS variables involves the colors of your designs. You can put them in variables instead of copying and pasting the same colors over and over.

1. Use in css

  • traditional way
body {
    
     background-color: #1e90ff; }

h2 {
    
     border-bottom: 2px solid #1e90ff; }

.container {
    
    
  color: #1e90ff;
  background-color: #ffffff;
  padding: 15px;
}

button {
    
    
  background-color: #ffffff;
  color: #1e90ff;
  border: 1px solid #1e90ff;
  padding: 5px;
}
  • Syntax for using the var() function
/* 我们声明两个全局变量(--blue 和 --white) */
:root {
    
    
  --blue: #1e90ff;
  --white: #ffffff;
}
/* 我们使用 var() 函数稍后在样式表中插入变量的值 */
body {
    
     background-color: var(--blue); }

h2 {
    
     border-bottom: 2px solid var(--blue); }

.container {
    
    
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
    
    
  --button-blue: #0000ff;
  background-color: var(--white);
  color: var(--button-blue);
  border: 1px solid var(--button-blue);
  padding: 5px;
}
  • The syntax of the var() function is as follows:
// name	必需。变量名(以两条破折号开头)。
// value 可选。回退值(在未找到变量时使用)。
var(name, value)

// 变量名称必须以两个破折号(--)开头,且区分大小写!
  • Basic usage:
1. 首先:CSS 变量可以有全局或局部作用域。

2. 全局变量可以在整个文档中进行访问/使用,而局部变量只能在声明它的选择器内部使用。

3. 如需创建具有全局作用域的变量,请在 :root 选择器中声明它。 :root 选择器匹配文档的根元素。

4. 如需创建具有局部作用域的变量,请在将要使用它的选择器中声明它。

2. Use in js

  • CSS variables can access the DOM, which means you can change them via JavaScript.
// 获取根元素
var r = document.querySelector(':root');

// 创建获取变量值的函数
function myFunction_get() {
    
    
  // 获取根的样式(属性和值)
  var rs = getComputedStyle(r);
  // 打印 --blue 变量的值
  console.log("--blue =", rs.getPropertyValue('--blue'))	// #1e90ff
}

// 创建设置变量值的函数
function myFunction_set() {
    
    
  // 把变量 --blue 的值设置为另一个值(在这里是 "lightblue")
  r.style.setProperty('--blue', 'lightblue');
}

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/131825694
Recommended