scss mixin 中的选择器是否有效? [英] Is selector inside a scss mixin valid?

查看:26
本文介绍了scss mixin 中的选择器是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般的CSS语法是

selector {
 declarations ...
}

我经常看到 mixin 处理了 declaration 部分

I have mostly seen mixin taking care of declaration part

示例

@mixin border-radius($rad) {
 border-radius: $rad;
}

// and used like 

some-selector {
 @include border-radius(5px)
}

但是mixin可以返回一个完整的选择器吗

but can a mixin return a complete selector itself

@mixin button {
  .button {
    color: red
  }
}

// now if I have button nested in any of my dom element I can say

selector-for-dom-element {
  @include button;
}

第二种情况是否有效语法?

is the second case valid syntax?

我已经看到它可以工作,但不确定它是否有文档记录以及我是否应该在生产中使用它.

I have seen that it works but not sure if its documented and should I use it in production.

作为对此的回答,我只是想确认其有效的语法以及对此类声明的任何引用.

as an answer to this, I am only looking to confirm that its valid syntax and any reference to such a claim.

或者我做错了,还有其他方法吗...除了使用extend?

Or I am doing it the wrong way, any other way to do it... except using extend?

推荐答案

是的,您当然可以在 mixin 中包含选择器,并且在 Sass 文档中有 示例.@mixin and @include 页面上的第一个代码示例实际上相当类似于您的示例,因为从类型选择器调用了一个 mixin,这会产生一个后代选择器.这是该示例的相关部分:

Yes, you can certainly include selectors within a mixin, and there are examples of this in the Sass documentation. The very first code example on the @mixin and @include page is actually quite similar to your example in that a mixin is called from a type selector, which results in a descendant selector. Here's the relevant part of that example:

@mixin horizontal-list {
  li {
    display: inline-block;
    margin: {
      left: -2px;
      right: 2em;
    }
  }
}

nav ul {
  @include horizontal-list;
}

编译为:

nav ul li {
  display: inline-block;
  margin-left: -2px;
  margin-right: 2em;
}

你的例子使用了类选择器,但原理是一样的.这是编译好的 CSS:

Your example uses a class selector, but the principle is the same. Here's the compiled CSS:

selector-for-dom-element .button {
  color: red;
}

这篇关于scss mixin 中的选择器是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆