Sass使用伪选择器扩展

Sim*_*mon 5 function sass extend mixins

我正在使用罗盘来管理mac osx上的一些sass文件.我有这些文件:

sass/
      screen.scss
            partials folder/
      ...
            _fonts.scss
            _functions.scss
      ...
Run Code Online (Sandbox Code Playgroud)

在字体中,我有这个规则,我想重用@extend.

//fonts.scss
.icon-ab-logo, {
font-family: 'icomoon';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
}
.icon-ab-logo:before { //i want to reuse this.
content: "\e000";
}
Run Code Online (Sandbox Code Playgroud)

在函数我有这个screen.scss:

.logo {
position: absolute;
top: 0;
bottom: 0px;
z-index: 500;
width: 9.5em;
background: $logo;
@include transition(all 0.2s);
   &:after{
     @include icon( ".icon-ab-logo" );
   }
 }
Run Code Online (Sandbox Code Playgroud)

最后在functions.scss中我称之为:

    @mixin icon( $icon ){
      font-family: 'icomoon';
      speak: none;
      font-style: normal;
      font-weight: normal;
      font-variant: normal;
      text-transform: none;
      line-height: 1;
      -webkit-font-smoothing: antialiased;
      @extend #{$icon}:before; //<- this is the problem, no errors just isn't parsed.
    }
Run Code Online (Sandbox Code Playgroud)

有没有办法引用.icon-ab-logo:在使用mixin之前?解决方法?谢谢阅读.

cim*_*non 9

如果要扩展伪类或伪元素,只需要扩展父选择器(即冒号前面的所有内容).

%foo:before {
  color: red;
}

.bar {
  @extend %foo;
}
Run Code Online (Sandbox Code Playgroud)

产生:

.bar:before {
  color: red;
}
Run Code Online (Sandbox Code Playgroud)

所以对于你的实例,你想要做的是:

.icon-ab-logo, {
    font: 100%/1 'icomoon'; // use the shorthand
    speak: none;
    text-transform: none;
    -webkit-font-smoothing: antialiased;
}

%foo:before, .icon-ab-logo:before { //i want to reuse this.
    content: "\e000";
}

@mixin icon( $icon ){
    font: 100%/1 'icomoon'; // use the shorthand
    speak: none;
    text-transform: none;
    -webkit-font-smoothing: antialiased;
    @extend #{$icon};
}

.bar {
    @include icon('%foo');
}
Run Code Online (Sandbox Code Playgroud)

请注意,您的mixin会产生很多样式,因此它不适合广泛重用.扩展它也会更有意义.


And*_*aus 5

似乎 SASS 不能很好地处理扩展中的伪元素。

像这样解决这个问题:

%before-icon
  color: red

.foo
  /* Some styles here */

  &:before
    @extend %before-icon
Run Code Online (Sandbox Code Playgroud)

结果:

.foo:before {
  color: red;
}

.foo {
  /* Some styles here */
}
Run Code Online (Sandbox Code Playgroud)

另外,看起来你把事情过于复杂化了。您会发现您的代码难以掌握和维护。

PS 你应该将 mixins 保留在_mixins.scss.