css - 带有嵌套&符号前缀的Sass mixin

标签 css sass scss-mixins

使用带有占位符选择器的混合来实现使用类前缀的能力的最佳方法是什么。

详细来说,假设我有一个具有 3 种尺寸的框类,但我希望可以选择使用不同的颜色。

我的基类是:

.box
.box-md
.box-sm

如果我希望任何基类框为绿色,我希望能够这样指定:

.box-green
.box-md-green
.box-sm-green

我怎样才能以尽可能干燥的方法做到这一点?

类似于此答案,但使用混合和占位符扩展:SCSS, how to @extend Nested ampersand "prefix"?

这是我到目前为止放在一起的东西(这是行不通的)

HTML:

<div class="box"></div>
<div class="box-green"></div>
<div class="box-sm"></div>
<div class="box-sm-green"></div>

CSS(SCSS):

// Main style placholder as mixin
@mixin box {
  height: 300px;
  width: 300px;
  margin: 20px;
  display: inline-block;
  background-color: blue;

  &-green {
    background-color: green;
  }
}

// Placeholders
%box {
  @include box;
}

%small-box {
  @include box;

  width: 100px;
  height: 100px;
}


// Class Definition
.box { @extend %box; }

.box-sm { @extend %small-box; }

笔:https://codepen.io/Aricha_MW/pen/xxKZWbV

最佳答案

这不是一个完整的答案,但确实构成了问题的解决方案:

我们的冠军是 @at-root 指令和此处的插值。该解决方案需要同时使用 mixins 和占位符选择器,并且有点困惑。

如果我们设置占位符选择器样式:

%box {
  height: 300px;
  width: 300px;
  margin: 20px;
  display: inline-block;
  background-color: blue;
}

%small-box {
    @extend %box;
    width: 100px;
    height: 100px;
}

然后我们可以让 mixin 为我们完成剩下的工作。

首先我们为我们想要的变体定义我们的mixin:

 @mixin green-bg($selector, $root) {
  // Takes element out of any nesting
  // Then we interpolate our argument variables 
  @at-root{
    #{$root}-green {
      // We can't set a placeholder as an argument so we'll just borrow the string and append the placeholder definer '%'
      @extend %#{$selector};
      background-color: green;
    }
  }
}

然后我们定义我们的 mixins 来帮助我们定义我们的类

@mixin box($parent) {

    @extend %box;

    @include green-bg(box, #{$parent});
}

@mixin small-box($parent) {

    @extend %small-box;

    @include green-bg(small-box, #{$parent});
}

当我们定义我们的类时,它们看起来像这样干净:

.box { @include box(&); }

.box-sm { @include small-box(&); }

这是最终产品的实际效果:https://codepen.io/Aricha_MW/pen/oNvxjEw

编辑:08/15/2019 - 这里的版本更简洁: https://codepen.io/Aricha_MW/pen/mdbPVXY

关于css - 带有嵌套&符号前缀的Sass mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57483951/

相关文章:

node.js - 在 Node.js 和 Sass 之间共享配置变量

html - 在 sas mixins 上工作以根据 margin 位置附加值

css - 如何在 SCSS 中使用属性作为属性值

javascript - 始终在特定的 div 上滚动

javascript - R Markdown : Remove container div when compiling to html

javascript - 在 HTML/Bootstrap 中连续滚动图像

android - Bootstrap 下拉菜单不适用于 Android

javascript - 如何在全局scss文件中实现绝对路径? VueJS

css - 用 compass 编译字体

angularjs - Sass错误: expected ")"