I'm not sure how to make a group selector in scss for this situation

0

Issue

I am trying to learn SCSS and encountered a small obstacle (if you can call it that) with something I am trying to do.

So the code beneath is probably a non-logical, simplified example of what I am trying to achieve.:

.gt-button {
  // some css
  &.gt-button-alt-l {
    font-size: 2em;
  }
}

.gt-buttonset {
  // some css
  &.gt-button-alt-l > .gt-button {
    font-size: 2em;
  }
}

This will generate:

.gt-button.gt-button-alt-l {
  font-size: 2em;
}

.gt-buttonset.gt-button-alt-l > .gt-button {
  font-size: 2em;
}

So I am wondering how to logically get underneath CSS instead:

.gt-button.gt-button-alt-l, .gt-buttonset.gt-button-alt-l > .gt-button {
  font-size: 2em;
}

How would I go about getting above generated CSS? I have fiddled around in Sassmeister.com but I cannot seem to get it in a way that is logical to me. I also don’t really know the technical term of joining those two CSS pieces into the desired generated CSS piece.

I do have to add that I did get it to work like this:

.gt-button {
  &.gt-button-alt-l, .gt-buttonset .gt-button-alt-l > & {
    font-size: 2em;
  }
}

But that for some reason does not seem logical to me. As .gt-buttonset is no child or anything of the .gt-button. So putting it there just feels weird.

I would appreciate to know if the last code fragment actually is the way to do this or if there are other options. If there are other options I would also like to know them.

Solution

If the outputted CSS is that important to you, you could leverage the @extend rule to achieve it:

Source SCSS:

.font-size-two { font-size: 2em; }

.gt-button {
  // some css
  &.gt-button-alt-l {
    @extend .font-size-two;
  }
}

.gt-buttonset {
  // some css
  &.gt-button-alt-l > .gt-button {
    @extend .font-size-two;
  }
}

Output CSS:

.font-size-two, .gt-buttonset.gt-button-alt-l > .gt-button, .gt-button.gt-button-alt-l {
  font-size: 2em;
}

Obviously, the downside is that you now also have an unused .font-size-two class in your CSS.

That said, you may be focusing too much on the nuances of the output CSS– as long as what you have in your SCSS is expressive, maintainable, and doesn’t generate a ton of superfluous CSS output, I would think that to be sufficient, and not worry that every possible optimization is being made. Remember that if you’re leveraging any other build tools there will be minification and potentially other optimizations, and that CSS is, ultimately, quite fast.

Answered By – Alexander Nied

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More