【问题标题】:SASS mixin with variable as selector带有变量作为选择器的 SASS mixin
【发布时间】:2018-12-07 14:56:18
【问题描述】:

我的目标是设计一堆需要大量代码的输入类型。当您还声明输入具有的各种状态时,其中大部分会被重用。

有没有一种 SASS 方法可以将“状态”变量传递给 mixin,然后将该 mixin 用作选择器?

这是我在https://www.sassmeister.com 插入以进行测试的(非工作)代码。

@mixin inputs($state) {
  input[type="text"]$state;
  input[type="email"]$state;
  input[type="url"]$state;
  input[type="search"]$state;
  input[type="date"]$state;
  input[type="time"]$state;
  /* etc */
}

@include inputs() {
  border:2px solid #ccc;
}

@include inputs(:hover) {
   border:2px solid #000;
}

@include inputs(:focus) {
   border:2px solid blue;
}

@include inputs(:active) {
   border:2px solid red
}

【问题讨论】:

    标签: css sass mixins


    【解决方案1】:

    您误用了 mixins,如 sass 文档中所述,mixins 必须包含声明。

    CSS 中有些东西写起来有点乏味,尤其是 CSS3 以及存在的许多供应商前缀。一个 mixin 可以让你创建组 您希望在整个站点中重用的 CSS 声明。你 甚至可以传入值以使您的 mixin 更加灵活。好用 mixin 用于供应商前缀。这是一个转换的例子。

    因此,如果 mixin 的属性不包含任何值,则会产生错误。

    如果您还原逻辑,它将起作用。您也可以在我的示例中添加更多变量,例如边框大小或类型。

    @mixin inputBorder($color) {
      border: 2px solid $color;
    }
    
    input[type="text"],
    input[type="email"],
    input[type="url"],
    input[type="search"],
    input[type="date"],
    input[type="time"] {
      @include inputBorder(#ccc);
    
      &:hover {
       @include inputBorder(#000);
      }
    
      &:focus {
       @include inputBorder(blue);
      } 
    
      &:active {
       @include inputBorder(red);
      }
    }
    

    如果您只想更改边框颜色,也可以使用@josephWebber 示例。

    【讨论】:

      【解决方案2】:

      您可以使用the sass ampersand 在不使用mixin 的情况下执行此操作。

      input[type="text"],
      input[type="email"],
      input[type="url"],
      input[type="search"],
      input[type="date"],
      input[type="time"] {
        border:2px solid #ccc;
        &:hover {
          border:2px solid #000;
        }
        &:focus {
          border:2px solid blue;
        }
        &:active {
          border:2px solid red;
        }
      }
      

      【讨论】:

      • 如果将来您想在其他东西上使用您的输入样式,您可以创建一个类或placeholder selector,将您的输入样式移入其中并在需要的地方扩展它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 2013-04-15
      • 2014-07-28
      相关资源
      最近更新 更多