简体   繁体   中英

Is selector inside a scss mixin valid?

CSS syntax in general is

selector {
 declarations ...
}

I have mostly seen mixin taking care of declaration part

example

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

// and used like 

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

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.

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

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

That compiles to:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM