meface/docs/article/web/css/cssvar.md

111 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: CSS自定义属性变量
date: 2021-01-11
author: ac
tags:
- CSS
categories:
- Web
---
> 复杂的网站中都会有大量的CSS代码通常也会有许多重复的值。我们可以将这些重复的值使用自定义属性变量来表示作为公共的CSS代码然后再其他地方引用这样更易于维护。
<!-- more -->
## CSS中的变量
### 1. 基本使用
变量的声明,语法:`--variableName`;
变量的使用,语法:`var(--variableName,defaultValue)`。
`variableName`:表示变量的名称,可以是数字字母下划线短横线`[0-9a-zA-Z_-]`进行组合。注意,大小写敏感。
`defaultValue`:表示默认值。当给定的变量值是未定义或无效不合法时,将会使用默认值。
```css
body{
--main-bg-color: #42b983
--text-color: #da5961
}
div{
background: var(--main-bg-colors,blue)
}
```
> 规则集所制定的选择器定义了自定义属性的可见作用域,即变量的作用域就是它所在的选择器的有效范围。
可以通过在 [`:root`](https://developer.mozilla.org/zh-CN/docs/Web/CSS/:root) 伪类上设置自定义属性,然后在整个文档需要的地方使用。
```css
/* 全局变量 */
:root{
--main-bg-color: #42b983;
}
/* 局部变量 */
div{
background: var(--main-bg-colors,blue)
}
```
### 2. 变量类型
**字符串**
可以与其他字符串拼接。
```css
--eq: 'learning';
--cd: var(--eq)' css';
```
**数值型**
数值不能与单位写在一起。
```css
.div{
--mit: 20;
/*无效*/
margin-top: var(--mit)px;
}
```
解决方法:
```css
/* 方式一:变量值带有单位,不能写成字符串*/
.div{
--mit: 20px;
margin-top: var(--mit);
}
/* 方式二使用calc()函数*/
.div{
--mit:20;
margin-top: calc(var(--mit)*1px);
}
```
### 3. JS中的值
在JavaScript中获取或者修改CSS变量和操作普通CSS属性是一样的
```javascript
element.style.getPropertyValue("--mit");
element.style.setProperty("--mit",newVaule);
```
## 参考文章
[1] `使用CSS自定义属性(变量)` https://developer.mozilla.org/zh-CN/docs/Web/CSS/Using_CSS_custom_properties
[2] `CSS 变量教程` http://www.ruanyifeng.com/blog/2017/05/css-variables.html