SCSS变量

vltsax25  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(80)

假设我有以下SCSS文件内容:

#id1 .class1 {
  input {
    padding: 4px;
    border: 0px none;
    &:disabled {
      color: red;
    }
  }
}

// .... other scss settings

.class2 #id2 .class3 {
  input {
    padding: 4px;
    border: 0px none;
    &:disabled {
      color: red;
    }
  }
}

字符串
正如你所注意到的,有重复的定义。那么基本上我怎么能写下面的伪代码呢

$var1: input {
          padding: 4px;
          border: 0px none;
          &:disabled {
            color: red;
          }
        }

#id1 .class1 {
  $var1
}

// .... other scss settings

.class2 #id2 .class3 {
  $var1
}


有可能以某种方式做到这一点吗?

gwo2fgha

gwo2fgha1#

您正在寻找的是@mixin

@mixin withInputStyles() {
  input {
    padding: 4px;
    border: 0px none;
    &:disabled {
      color: red;
    }
  }
}

#id1 .class1 {
  @include withInputStyles;
}

.class2 #id2 .class3 {
  @include withInputStyles;
}

字符串

CSS输出

#id1 .class1 input {
  padding: 4px;
  border: 0px none;
}
#id1 .class1 input:disabled {
  color: red;
}

.class2 #id2 .class3 input {
  padding: 4px;
  border: 0px none;
}
.class2 #id2 .class3 input:disabled {
  color: red;
}


如果你不想复制样式,另一种可能性是使用@extendplaceholder selector

%inputStyles {
  input {
    padding: 4px;
    border: 0px none;
    &:disabled {
      color: red;
    }
  }
}

#id1 .class1 {
  @extend %inputStyles;
}

.class2 #id2 .class3 {
  @extend %inputStyles;
}

CSS输出

.class2 #id2 .class3 input, #id1 .class1 input {
  padding: 4px;
  border: 0px none;
}
.class2 #id2 .class3 input:disabled, #id1 .class1 input:disabled {
  color: red;
}

相关问题