【问题标题】:Avoid double writing styles避免双重书写风格
【发布时间】:2015-07-22 01:27:55
【问题描述】:

我想知道如果某些样式对于一个元素是相同的并且可能是伪类,我该如何避免编写两次:

.element {
  color: #a0c225;
  &:hover {
    color: #a0c225;
  }
  &:focus {
    color: #a0c225;
  }
}

我不想在SASS 中重复#a0c225 的颜色?

【问题讨论】:

    标签: html css sass


    【解决方案1】:

    我会使用这样的东西:

    $col-example: #a0c225;
    
    %class-example {
      color: $col-example
    }
    
    .element {
      @extend %class-example;
      /* more properties */
      &:hover {
        @extend %class-example;
        /* more properties */
      }
      &:focus {
        @extend %class-example;
        /* more properties */
      }
    }
    

    将编译为:

    .element, .element:hover, .element:focus {
        color: #a0c225;
    }
    
    .element {
      /* more properties */
      &:hover {
        /* more properties */
      }
      &:focus {
        /* more properties */
      }
    }
    

    【讨论】:

    • 感谢您的回答。我很确定有类似& 的方法有效。我不一定需要存储变量。
    • 如果您没有指定任何其他颜色用于聚焦和悬停,颜色将完全保持正常状态
    【解决方案2】:

    你可以使用& 来做这样的事情:

    .element {
        &, &:hover, &:focus {
            color: #a0c225;
        }
    }
    

    编译成:

    .element, .element:hover, .element:focus {
        color: #a0c225;
    }
    

    【讨论】:

    • 这就是我要找的东西!
    • @supersize 很高兴能够提供帮助
    • @Alex 如果你看一下:stackoverflow.com/questions/13608855/… 你会注意到& 符号不是 CSS,它是连接选择器的 SASS/LESS 方式,所以这是一个有效的答案最适合我的需要!
    • 是的,你是对的,对我来说它太接近 css 而不需要 sass ;)
    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多