【问题标题】:Sass @each loop for attribute selector属性选择器的 Sass @each 循环
【发布时间】:2018-07-25 20:34:10
【问题描述】:

我在@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;
}

【问题讨论】:

  • 你为什么要这样做,如果他们都共享相同的样式,为什么不给他们一个共享的类?
  • @Pete 我离开我的电脑并意识到同样的事情然后看到了这条评论。 ???好点子!

标签: css sass


【解决方案1】:

您使用的$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'] {
    /** ... */
}

【讨论】:

  • @Pete 提出了一个很好的观点。但是,这确实有效,现在我将知道将来如何实施。谢谢!
  • @AndrewC.Duarte - 查看更新以生成一条规则。
  • 哇!这真太了不起了。谢谢!
猜你喜欢
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多