Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSS变量 var() #196

Open
TieMuZhen opened this issue May 8, 2022 · 0 comments
Open

CSS变量 var() #196

TieMuZhen opened this issue May 8, 2022 · 0 comments
Labels

Comments

@TieMuZhen
Copy link
Owner

用法

CSS中原生的

  • 变量定义语法是:--*
  • 变量使用语法是:var(--*)

其中*表示我们的变量名称。

实际应用

当我们响应式变化的时候,改变的CSS属性值不是1个,而是3个或者更多,如果我们有3个响应点,是不是就至少需要9个CSS声明?但是,由于我们有了CSS变量,同时,CSS变量可以传递,当我们遭遇响应点的时候,我们只需要改变一个CSS属性值就可以了。

下面就是本demo核心CSS代码(只需要改变--columns这一个变量即可):

.box {
    --columns: 4;
    --margins: calc(24px / var(--columns));
    --space: calc(4px * var(--columns));
    --fontSize: calc(20px - 4 / var(--columns));
}
@media screen and (max-width: 1200px) {
    .box {
        --columns: 3;
    }
}
@media screen and (max-width: 900px) {
    .box {
        --columns: 2;
    }
}
@media screen and (max-width: 600px) {
    .box {
        --columns: 1;
    }
}

通过使用变量大大简化了媒体查询的代码

参考文献

@TieMuZhen TieMuZhen added the CSS label May 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant