简体   繁体   中英

Extending a Nested Placeholder in SCSS

Is it possible to @extend a SCSS placeholder with nesting, and have that nesting reflected in the resulting class?

Given a nested placeholder:

%my-form-field {
  ...

  &__label {
    ...
  }

  &__feedback {
    ...
  }
}

I currently have to do the following:

.one-of-many-targets {
  @extend %my-form-field;

  &__label {
    @extend %my-form-field__label;
  }

  &__feedback {
    @extend %my-form-field__feedback;
  }
}

But I'd like to be able to simplify this to:

.one-of-many-targets {
  @extend %my-form-field;
}

... and have it resolve to:

.one-of-many-targets { ... }
.one-of-many-targets__label { ... }
.one-of-many-targets__feedback { ... }

Is there a different way to write my placeholder and @extends to make the SCSS cleaner, as in the 2nd example?

You can use a mixin instead:

@mixin my-form-field() {
  width: 10px;
  &__label {
    width: 20px;
  }

  &__feedback {
     width: 30px;
  }
}

.one-of-many-targets {
  @include my-form-field();
}

will generate:

.one-of-many-targets {
  width: 10px;
}
.one-of-many-targets__label {
  width: 20px;
}
.one-of-many-targets__feedback {
  width: 30px;
}

You could try use selector.append()

See:https://github.com/sass/sass/issues/2808#issuecomment-574413393

Also see more info why parent selector didn't work as you expect in extend-only selectors:https://github.com/sass/sass/issues/2262#issuecomment-291645428

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM