【问题标题】:Sass ampersand when base uses pseudo-element (before / after)基础使用伪元素时的 Sass & 符号(之前/之后)
【发布时间】:2016-02-10 05:07:51
【问题描述】:

我有多个 div::before 共享 90% 的样式,我想使用 SASS 的嵌套结构来设置它们的样式,以便仅指定差异,同时保持它们分组。但是当将成为& 的基础已经在使用伪元素时,我找不到该怎么做。这样做时:

SASS

#home .foo .bar::before {
    content: "";
    position: absolute;
    margin: 2px;
    background: url("images/baz.png") 0 0 no-repeat;
    height: 39px;
    width: 56px;

    &.item-1 {
        top: 0;
        right: 0;
    }        
    &.item-2 {
        top: 10px;
        right: 20px;
    }
    &.item-3 {
        top: 40px;
        right: 60px;
    }
    ...
}

输出 CSS

#home .foo .bar::before {
    content: "";
    position: absolute;
    margin: 2px;
    background: url("images/baz.png") 0 0 no-repeat;
    height: 39px;
    width: 56px;

#home .foo .bar::before.item-1 {
    top: 0;
    right: 0;
}        
#home .foo .bar::before.item-2 {
    top: 10px;
    right: 20px;
}
#home .foo .bar::before.item-3 {
    top: 40px;
    right: 60px;
}
...

当然,问题是 & 符号与 ::before 一起使用整个根,并在其末尾添加类 .item-x,因此 css 规则不起作用。我想要的输出是#home .foo .bar.item-2::before。我什至不确定是否可以这样嵌套,所以任何帮助都会很好。

感谢您的帮助!

【问题讨论】:

    标签: css sass


    【解决方案1】:

    我认为这是你最好的选择:

    #home .foo .bar {
      &:before {
        content: "";
        position: absolute;
        margin: 2px;
        background: url("images/baz.png") 0 0 no-repeat;
        height: 39px;
        width: 56px;
      }
    
      &.item-1 {
        &:before {
          top: 0;
          right: 0;
        }
      }
    
      …
    }
    

    演示:http://www.sassmeister.com/gist/d2d89f0d7070a3473a6c

    如果您愿意,也可以写成&.item-1:before {…}

    【讨论】:

    • 简单、整洁、智能
    • 是的,我认为这是最好/最简单的选择。谢谢
    【解决方案2】:

    @at-root 在这里可能有助于保持样式分组,同时控制根是什么。看看这个:

    #home .foo .bar::before {
        content: "";
        position: absolute;
        margin: 2px;
        background: url("images/baz.png") 0 0 no-repeat;
        height: 39px;
        width: 56px;
    
      @at-root #home .foo .bar.item1::before {
        top: 0;
        right: 0;
      }
    
      @at-root #home .foo .bar.item2::before {
        top: 10px;
        right: 20px;
      }
    
      @at-root #home .foo .bar.item2::before {
        top: 40px;
        right: 60px;
      }
    }
    

    输出为:

    #home .foo .bar::before {
      content: "";
      position: absolute;
      margin: 2px;
      background: url("images/baz.png") 0 0 no-repeat;
      height: 39px;
      width: 56px;
    }
    #home .foo .bar.item1::before {
      top: 0;
      right: 0;
    }
    #home .foo .bar.item2::before {
      top: 10px;
      right: 20px;
    }
    #home .foo .bar.item2::before {
      top: 40px;
      right: 60px;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 2014-10-31
      • 2023-03-21
      • 2015-04-10
      相关资源
      最近更新 更多