SASS / SCSS @extend rule selectors

2019-02-16 07:26发布

问题:

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??

回答1:

Nested selectors cannot be extended - in fact, that's the syntax error that is reported by the parser. Structural comments aside (I can't think of a scenario where the above @extend relationship is warranted), this is not something that can be currently accomplished with SASS.

NB: this is, however supported by Stylus if you're open to it.



回答2:

An obvious solution whould be to define a new @mixin your-name for your .content-header h1 definitions and @include your-name within .box-header h1.

But, there is a much better solution Referencing Parent Selectors: & :

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

It's not obvious because the logic reverse but it's better to maintain. You are changing the definitions of h1 for a specific selector.



回答3:

Nested @extend is not allowed. Try this for a work around

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

Some thing I constructed for my personel use below sharing with you all, This dynamically constructs the selector, Since special characters are not allowed in naming conventions I used '--' to seperate class

$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();

Good Luck!!



回答4:

As already said, you can only extend a single class. Generally, nesting with extend should be skipped. There is more about extend and its options in this text.



标签: css sass