css的:root和[]属性选择器

css的:root和[]属性选择器是页面css设置的常用操作,比如要切换暗黑模式或者颜色主题,就可以这样写:

:root[mode='light'] {
  --blog-bg-color: #fff;
  --text-color: #314659;
  --border-color: #ccc;
  --catalog-bg-color: #fff;
  --panel-bg-color: #f8f8f8;
  --contents-bg-color: #fff;
  --code-bg-color: #f5f5f5;
}
:root[mode='dark'] {
  --blog-bg-color: #202020;
  --text-color: #d8d8d8;
  --border-color: #2f2f2f;
  --catalog-bg-color: #252525;
  --panel-bg-color: #3a3a3a;
  --contents-bg-color: #343232;
  --code-bg-color: #3a3a3a;
}
:root[theme='a'] {
  --theme-color: #2d8cf0;
}
:root[theme='b'] {
  --theme-color: #fa7298;
}
:root[theme='c'] {
  --theme-color: #42b983;
}
:root[theme='d'] {
  --theme-color: #607d8b;
}
:root[theme='e'] {
  --theme-color: #5e72e4;
}
:root[theme='f'] {
  --theme-color: #ff9700;
}
:root[theme='g'] {
  --theme-color: #ff5722;
}
:root[theme='h'] {
  --theme-color: #009688;
}
:root[theme='i'] {
  --theme-color: #673bb7;
}
:root[theme='j'] {
  --theme-color: #906f61;
}

其中:root表示文档根元素,非IE及ie8及以上浏览器都支持,在:root中声明相当于全局属性,在使用时我们就可以简单地通过var(--css_variable)的方式来进行使用,在根元素上面的属性切换的时候,比如them属性从i切换到了j,这时候相应的颜色就会跟着改变。

posted @ 2021-12-30 21:37  Bravo_Jack  阅读(699)  评论(0编辑  收藏  举报