19

I'm having a little problem with the @extend rule, this is what I got (focus on the 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
    }
}

So it will be:

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

But it seems like @extend don't like that, is any other way to write this without giving the h1 a class??

4

4 回答 4

9

嵌套选择器无法扩展——事实上,这是解析器报告的语法错误。除了结构性注释(我想不出@extend有理由保证上述关系的情况),这不是目前可以用 SASS 完成的事情。

注意:如果您愿意, Stylus会支持它。

于 2012-06-25T22:49:35.480 回答
6

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

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

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

这并不明显,因为逻辑相反,但最好保持。您正在更改h1特定选择器的定义。

于 2013-05-26T14:21:32.320 回答
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();

祝你好运!!

于 2016-03-23T04:49:19.317 回答
0

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

于 2018-03-13T11:16:30.470 回答