Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

bem - Is it possible to include the parent properties in an extended Sass class?

I'd like to implement something like the BEM model in my Sass library. But I'm struggling to find a clean way to do this.

For example, I'd like to declare a 'base' style for a common element, and then extend it with useful variations:

.container {
  margin: 10%;
  background: #eee;

  &-featured {
    border: 2px solid #999;
  }

}

The problem here is that the generated .container-featured class only contains the border property—Sass doesn't include the margin and background from its 'parent' class.

So you end up having to double up on classes in your markup to get the desired results:

<div class="container container-featured">
  ...
</div>

Is there some way to pull the properties from a parent class down into that modifier class, so you can get the same visual result just referencing the modifier class in your markup?

<div class="container-featured">
  <!-- has margin, background, and border styles via just modifier class -->
</div>

I've tried using mixins to do this, but things get verbose and repetitive very quickly:

@mixins container {
  margin: 10%;
  background: #eee;
}

.container {
  @include container;

  &-featured {
    @include container;
    border: 2px solid #999;
  }

}

Is there a simple, clean way of achieving this with Sass?

question from:https://stackoverflow.com/questions/65909691/scss-ampersand-not-working-when-trying-to-make-modifiers-for-class-names

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you are looking for is the @extend directive. @extend allows you share a set of CSS properties from one selector to another. This means that you would only need to use the container-featured class.

Example

.container {
  margin: 10%;
  background: #eee;

  &-featured {
    @extend .container;
    border: 2px solid #999;
  }
}

compiles to:

.container,
.container-featured {
    margin: 10%;
    background: #eee;
}

.container-featured {
    border: 2px solid #999;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...