SASS / SCSS @extend规则选择器

时间:2012-06-25 22:42:41

标签: css sass

我对@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 个答案:

答案 0 :(得分:9)

嵌套选择器无法扩展 - 实际上,这是解析器报告的语法错误。抛开结构性评论(我无法想到上述@extend关系得到保证的情况),这不是目前SASS可以实现的目标。

注意:如果您愿意,Stylus支持此功能。

答案 1 :(得分:4)

一个明显的解决方案是为@mixin your-name定义新.content-header h1@include your-name定义.box-header h1

但是,有一个更好的解决方案Referencing Parent Selectors: &

h1 {
    .content-header &,
    .box-header & {
        // CSS properties
    }
    .box-header & {
        // And his own CSS properties
    }
}

这并不明显,因为逻辑反转但维护得更好。您正在更改特定选择器的h1定义。

答案 2 :(得分:0)

不允许使用嵌套的@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();

祝你好运!!

答案 3 :(得分:0)

如前所述,您只能扩展一个类。通常,应跳过使用extend进行嵌套。在this text中有更多关于扩展及其选项的内容。

相关问题