Sass @each循环的属性选择器

时间:2018-07-25 11:58:04

标签: css sass

我在@each循环中输出属性选择器时遇到麻烦。 CSS输出呈现'{$type}'。我将如何正确执行此操作?

SASS

@each $type in text, email 
  input[type='{$type}']
    background-color: $white
    border: 2px solid $loblolly
    border-radius: 6px
    color: $black
    font-family: $gotham
    font-size: $h5
    height: 2.75rem
    padding: 0 .625rem 0 .3125rem
    text-indent: .3125rem
    transition: border-color .5s ease background-color .5s ease

CSS(输出)

input[type='{$type}'] {
  background-color: #fff;
  border: 2px solid #c4d0d6;
  border-radius: 6px;
  color: #242934;
  font-family: "Gotham A", "Gotham B", Helvetica, Arial, sans-serif;
  font-size: 1.125rem;
  height: 2.75rem;
  padding: 0 0.625rem 0 0.3125rem;
  text-indent: 0.3125rem;
  transition: border-color 0.5s ease background-color 0.5s ease;
}

input[type='{$type}'] {
  background-color: #fff;
  border: 2px solid #c4d0d6;
  border-radius: 6px;
  color: #242934;
  font-family: "Gotham A", "Gotham B", Helvetica, Arial, sans-serif;
  font-size: 1.125rem;
  height: 2.75rem;
  padding: 0 0.625rem 0 0.3125rem;
  text-indent: 0.3125rem;
  transition: border-color 0.5s ease background-color 0.5s ease;
}

1 个答案:

答案 0 :(得分:3)

您使用$type变量错误。您需要将{$type}替换为#{$type}

@each $type in text, email 
  input[type='#{$type}']
    background-color: $white
    border: 2px solid $loblolly
    border-radius: 6px
    color: $black
    font-family: $gotham
    font-size: $h5
    height: 2.75rem
    padding: 0 .625rem 0 .3125rem
    text-indent: .3125rem
    transition: border-color .5s ease background-color .5s ease

您还可以将规则生成为Pete mentioned

$white: #fff
$loblolly: green
$black: black
$gotham: 'sans-serif'
$h5: 16px

%input-styles 
  background-color: $white
  border: 2px solid $loblolly
  border-radius: 6px
  color: $black
  font-family: $gotham
  font-size: $h5
  height: 2.75rem
  padding: 0 .625rem 0 .3125rem
  text-indent: .3125rem
  transition: border-color .5s ease background-color .5s ease

@mixin input-types
  @each $type in text, email
    input[type='#{$type}'] 
      @extend %input-styles

@include input-types

这将产生以下输出:

input[type='text'], input[type='email'] {
    /** ... */
}