是否可以在扩展的

是否可以在扩展的

本文介绍了是否可以在扩展的 Sass 类中包含父属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 Sass 库中实现类似 BEM 模型的东西.但我正在努力寻找一种干净的方法来做到这一点.

例如,我想为一个公共元素声明一个基本"样式,然后用有用的变体对其进行扩展:

.container {保证金:10%;背景:#eee;&-特色{边框:2px 实心 #999;}}

这里的问题是生成的 .container-featured 类只包含边框属性——Sass 不包含来自其父"类的边距和背景.

因此,您最终不得不将标记中的类加倍以获得所需的结果:

...

是否有某种方法可以将属性从父类下拉到该修饰符类中,这样您只需在标记中引用修饰符类就可以获得相同的视觉结果?

<!-- 仅通过修饰符类具有边距、背景和边框样式 -->

我已经尝试使用 mixins 来做到这一点,但事情变得冗长和重复:

@mixins 容器 {保证金:10%;背景:#eee;}.容器 {@include 容器;&-特色{@include 容器;边框:2px 实心 #999;}}

是否有使用 Sass 实现这一目标的简单、干净的方法?

解决方案

您正在寻找的是 @extend 指令.@extend 允许您将一组 CSS 属性从一个选择器共享到另一个选择器.这意味着您只需要使用 container-featured 类.

示例

.container {保证金:10%;背景:#eee;&-特色{@extend .container;边框:2px 实心 #999;}}

编译为:

.container,.container-featured {保证金:10%;背景:#eee;}.container-featured {边框:2px 实心 #999;}

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?

解决方案

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;
}

这篇关于是否可以在扩展的 Sass 类中包含父属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:14