前言
记录日常css变量的一些使用技巧, 方便在自己忘记时,及时查阅.
一、原生css变量
1、基础用法
定义变量使用 “--” + 变量名 css变量具有作用域, 子元素只能使用父级元素内定义的css变量 想要定义全局变量, 可以在:root下进行定义
<body>
<div class="test"></div>
<div class="test_1">
<div class="test_1_1"></div>
</div>
<div class="test_2">
<div class="test_2_1"></div>
</div>
</body>
<style>
:root{
--width:200px;
--height:200px;
--color:red;
}
.test{
height:var(--height);
width:var(--width);
background-color:var(--color)
}
.test_1{
--color1:blue;
}
.test_1_1{
height:var(--height);
width:var(--width);
background-color:var(--color1)
}
.test_2_1{
height:var(--height);
width:var(--width);
background-color:var(--color1) // 无效,不在css变量的作用域内
}
</style>
2、js定义css变量/行内定义变量
<body>
<style>
.test_1 {
width: 200px;
height: 200px;
background-color: var(--color)
}
.test_2{
width:200px;
height:200px;
background-color:var(--color1);
}
</style>
<!-- js定义 -->
<div class="test">
<div class="test_1"></div>
</div>
<!-- 行内定义 -->
<div class="test1" style="--color1: blue">
<div class="test_2"></div>
</div>
<script>
var div = document.querySelector('.test');
div.style.cssText = '--color:red'
</script>
</body>
注意
div.style.cssText会覆盖行内样式, 所以不能和行内同时使用
二、css3的currentColor关键字
可以指代最近的父级的color. 如果你使用过antd的icon组件,一定知道, icon的颜色取决于父级的color颜色. 明明是svg的fill属性填充的颜色,为什么会使用到父级的color呢? 原因就是使用了currentColor
<body>
<style>
.test {
color: blue;
}
.test_1 {
width: 200px;
height: 200px;
background-color: currentColor;
}
</style>
<div class="test">
<div class="test_1"></div>
</div>
</body>
三、通过dom自定义属性, 替换伪元素内容
正常使用伪元素
<body>
<style>
.test::after {
content: 'test';
color: blue;
}
</style>
<div class="test"></div>
</body>
这样的使用方式, 能用到的场景实在有限, 大部分的业务场景要求content的内容是动态的,写死在css中,将没有意义. 但是如何使用js来控制content的内容呢?
js替换伪元素内容
答案是利用dom的自定义属性来做. 这里也将要使用要一个新的css函数
<body>
<style>
.test::after {
content: attr(data-hint);
color: blue;
}
</style>
<div class="test" data-hint="不知名前端"></div>
<script>
window.document.documentElement.onclick = () => {
var target = document.querySelector('.test')
target.setAttribute('data-hint', '不知名前端-不知名')
}
</script>
</body>
刷新页面后, 点击任意位置, 看到了什么?
总结
本着能用css, 绝不动用js的原则, 学会css的各种奇淫巧技还是有比较的哇