在@if scss 中使用 css 变量

问题描述

在创建样式的过程中,我有一个想法,即创建一个 CSS 变量来表示要显示或不显示透明度的布尔值,但不幸的是,我看到条件不起作用!

main.css

:root {
    --navbar-transparent: "true";
  }

navbar.component.scss

@if var(--navbar-transparent) == "true" {
.nav-booking {
    position: absolute;
    width: 100%;
    background: transparent;
    padding-top: 20px;
  }
} @else {
.nav-booking{
    border-bottom: 2px solid #d6d1d180;
 }
}

有没有办法用 css 变量来做到这一点?否则不可能!

解决方法

你可以hack一个像下面这样的if() {},但我怀疑你能做一个if() {} else {}

* {
  --navbar-transparent: true;
  
}

.nav-booking {
    /* if !true */
    padding:var(--navbar-transparent,20px);
    border:var(--navbar-transparent,5px solid green);
    /*  */
    
    background:red;
    height:10px;
    margin:10px;
 }
<div class="nav-booking" ></div>

<!-- you need to set "initial" to get your false -->
<div class="nav-booking" style="--navbar-transparent:initial"></div>

有关获取有关使用 initial 的模式详细信息

How to store inherit value inside a CSS variable (aka custom property)?

CSS custom properties (variables) for box model

,

不幸的是,在 sass 中,自定义属性仅被视为字符串,它不关联值。

但是有解决方法:

@function get($var) {
  @return map-get($custom-properties,$var);
}

$custom-properties: ();

@each $key,$value in $custom-properties {
  :root {
    --#{$key}: #{$value};
  }
}

将要在 Sass 项目中使用并编译为自定义属性的任何变量添加到此映射:$custom-properties: ();

$custom-properties: (
  'navbar-transparent': true,//...
);

现在使用 get($var) 访问 Sass 项目中的上述变量。

@function get($var) {
  @return map-get($custom-properties,$var);
}

$custom-properties: (
  'navbar-transparent': true,);

@each $key,$value in $custom-properties {
  :root {
    --#{$key}: #{$value};
  }
}

@if (get(navbar-transparent)) {
  .nav-booking {
    position: absolute;
    width: 100%;
    background: transparent;
    padding-top: 20px;
  }
} @else {
  .nav-booking{
    border-bottom: 2px solid #d6d1d180;
  }
}

这将编译为:

:root {
  --navbar-transparent: true;
}

.nav-booking {
  position: absolute;
  width: 100%;
  background: transparent;
  padding-top: 20px;
}

https://codepen.io/LudwigGeorgImmanuel/pen/dypaXyE

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...