css变量 基础知识整理

css变量 基础知识整理

css变量,欢迎观看Altaba的博客

前言: CSS 变量是由CSS作者定义的实体,其中包含要在整个文档中重复使用的特定值。使用自定义属性来设置变量名,并使用特定的 var() 来访问。

1、变量的声明及作用域

css变量的声明是使用 “–”,

区分大小写

作用域之能是在当前声明的选择器下,可在内部元素中再次声明进行覆盖,同css属性

html {
  --fan: #7F583F;
  --wei: #F7EFD2;
}

:root{
	--mainColor:red; // 这让该自定义属性能在全局可用(它匹配<html>元素内的所有内容)。
}

/* 无效的 */
--color:;
/* 有效的 */
--color: ; /* 值是空格 */
2、变量的使用

var()函数来读取变量值,var()函数可以传入两个参数,第二个表示变量的默认值。如果该变量不存在,就会使用这个默认值。变量值只能作为属性值,不能作为属性名

.div{
    color: var(--fan,'red');
}
3、变量值的类型(字符串,数字,带单位的css代码块)
html {
  --fan: 20;
  --wei: 20px;
  --ruan: '你好';
}

// 使用
div{
    font-size: calc(var(--fan) * 1px); // 数值必须使用calc()函数,将它们连接。
    padding: var(--wei); // 如果变量值带有单位,就不能写成字符串
    content: var(--ruan)'Altaba'; // 变量值是一个字符串,可以与其他字符串拼接。
}
4、实现响应式编程

配合响应式布局的media命令里面声明变量,可实现响应式的样式改变

body {
  --primary: #7F583F;
  --secondary: #F7EFD2;
}

a {
  color: var(--primary);
  text-decoration-color: var(--secondary);
}

@media screen and (min-width: 768px) {
  body {
    --primary:  #F7EFD2;
    --secondary: #7F583F;
  }
}
5、兼容性,可通过以下方式检测

![image-20190102195233650](/Users/vistwang/Library/Application Support/typora-user-images/image-20190102195233650.png)

// css检测
@supports ( (--a: 0)) {
  /* supported */
}

@supports ( not (--a: 0)) {
  /* not supported */
}
// js 检测
const isSupported =
  window.CSS &&
  window.CSS.supports &&
  window.CSS.supports('--a', 0);

if (isSupported) {
  /* supported */
} else {
  /* not supported */
}
6、通过JavaScript操作CSS变量

可以直接通过JavaScript代码访问CSS变量。通过 getComputedStylesetPropertygetPropertyValue从JavaScript访问CSS变量非常简单。 要获取变量,请使用 getPropertyValue()

例如

.navbar {
	--eui-select: 100px;
}
// 获取变量 (方式1)
// 缓存你即将操纵的元素
const sidebarElement = document.querySelector('.sidebar');
// 缓存sidebarElement的样式于cssStyles中
const cssStyles = getComputedStyle(sidebarElement);
// 获取 --left-pos CSS变量的值
const cssVal = String(cssStyles.getPropertyValue('--left-pos')).trim();
// 将CSS 变量的值打印到控制台: 100px
console.log(cssVal);

// 设置变量
sidebarElement.style.setProperty('--left-pos', '200px');

// 获取和设置变量 方式2
/* 从 :root 根元素获取变量值 */
document.documentElement.style.getPropertyValue('--background');
/* 从 .block-3 元素获取变量值 */
document.querySelector('.block-3').style.getPropertyValue('--background');

// 改变变量
/* 修改 :root 根元素的变量值 */
document.documentElement.style.setProperty('--background', '#ff0000');
/* 修改 .block-3 元素的变量值 */
document.querySelector('.block-3').style.setProperty('--background', '#ff0000');

20190102 晚

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值