css - @mixin 使用参数选择一个特定的占位符

标签 css sass

我正在尝试在占位符内使用带有参数的混合。 这个想法是使用一行代码来选择类中的特定占位符。 实际上,我不知道是否有另一种更好的方法来做到这一点,也许是一个功能或其他。 我正在学习 Sass,所以我正在尝试进行实验。

HTML

<div class='wrap'>
  <div class='box'></div>
  <div class='box'></div>
</div>

SCSS

// VAR
$size-xs: 30px;
$size-s: 50px;
$size-m: 70px;

$color-1: orange;
$color-2: rgb(34,139,86);

@mixin box($val) {
  %box-one {
    width: $size-s;
    height: $size-s;
    background: $color-1;
    margin: auto;
    border-radius: 6px;
  }
  %box-two {
    width: $size-s;
    height: $size-s;
    background: $color-2;
    margin: auto;
    border-radius: 6px;
  }
  .box {
    @extend #{$val} !optional;
  }
}

.wrap {
  width: 100%;
  height: 100px;
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  @include box(box-one);
}

谢谢!

最佳答案

目前,您的代码无法正常工作,因为您忘记在 #{$val}<​​ 之前添加 %:

.box {
  @extend %#{$val} !optional;
}

无论如何,将占位符选择器放在混入中并不是一个好主意,因为每次调用混入时,您都在创建新的选择器。这意味着例如如果您添加:

.randomSelector {
  @include box(box-one);
}

您将获得:

.wrap .box { ... }
.randomSelector .box { ... }

代替:

.randomSelector .box, .wrap .box { ... }

所以我建议您将 %box-one%box-two 外部化。

最后一件事,如果这两个类之间的唯一区别是 background 属性,也许使用单个类重新组合公共(public)属性将是更好的优化:

.box {
  width: $size-s;
  height: $size-s;
  margin: auto;
  border-radius: 6px;
}

%box-one {
  background: $color-1;
}

%box-two {
  background: $color-2;
}

@mixin box($val) {
  .box {
    @extend %box-#{$val} !optional;
  }
}

.wrap {
  width: 100%;
  height: 100px;
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  @include box(one);
}

如果您有更多框样式,您甚至可以动态创建占位符:

$boxStyles: (
  one: $color-1,
  two: $color-2
);

@each $box, $style in $boxStyles {
  %box-#{$box}  {
    background: $style;
  }
}

关于css - @mixin 使用参数选择一个特定的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56098824/

相关文章:

css - 试图将我的博客标题向上移动

sass - WebPack + SASS : How to generate relative image path?

python - Django 静态文件和 settings.py 中的文件路径

html - CSS - 如何排列 div 和文本

html - 如何将列表项置于菜单项的前面?

css - 如何将::after背景图像放置到div的中心?

css - Gulp-sass 编译 scss 文件失败

css - 如何使用 webpack 从 MDL 获取 svg

css - 变量sass的问题

html - 中间对齐一个粘性列