SASS/SCSS @extend规则选择器

19

我在使用@extend规则时遇到了一点问题,这是我的代码(请关注h1):

.content-header {
    // CSS properties
    h1 {
        // CSS properties
    }
}

.box-header {
    // CSS properties
    h1 {
        @extend .content-header h1; // My selector problem!
        // And his own CSS properties
    }
}

所以它将是:

.content-header h1, .box-header h1 {
    /* Happily sharing the same CSS properties */
}

但似乎@extend不喜欢那样做,是否有其他方法可以在不给h1添加类的情况下编写此内容?

4个回答

10
嵌套选择器无法扩展 - 实际上,这是解析器报告的语法错误。除了结构注释之外(我想不出上面的@extend关系有何必要的情况),目前无法在SASS中实现此功能。
注意:如果您愿意,Stylus支持此功能。

6
一个显而易见的解决方案是为你的`.content-header h1`定义一个新的`@mixin your-name`,并在`.box-header h1`中使用`@include your-name`。
但是,有一个更好的解决方案:参考父选择器`&`。请查看Sass官方文档
h1 {
    .content-header &,
    .box-header & {
        // CSS properties
    }
    .box-header & {
        // And his own CSS properties
    }
}

虽然逻辑相反,但更易于维护。您正在为特定选择器更改h1的定义。


1

不允许嵌套@extend。尝试以下方法进行解决

.foo {
  background-color: lime;    
}
.b{
  margin:0px;
}
.baz {
  @extend .foo;
  @extend .b;
}

这是我为个人使用而构建的东西,现在与所有人分享。它动态构建选择器,由于命名约定中不允许特殊字符,因此我使用“--”来分隔类。

$ih-classes: ( "module--cardContainer--header",
                "a"
              );
  %module--cardContainer--header {
    color: #1e1d1c;
    background-color: #fff;
    border-bottom: 0.0714rem solid #e0dddc;
    padding: 0;
    line-height: 3.1429rem;
    font-size: 1.2857rem;
    font-family: ProximaNovaSemiBold;
}
%a{
  color:red;
}

@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);

  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }

  @return $string;
}
@mixin generate-framework-code() {

              @each  $icon in $ih-classes {
               $val : str-replace($icon, '--', ' .');
                  .#{$val} {
                            @extend %#{$icon};
                         }
                  }
}

@include generate-framework-code();

祝你好运!


0

正如先前所提到的,您只能扩展单个类。通常应跳过使用 extend 进行嵌套。关于 extend 及其选项的更多信息,请参见 this text


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接