Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use @at-root and & in list of selectors

Tags:

sass

I have a CSS I try to move to SASS with many structures like

.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
...
}

With this:

 .btn-primary {
    ...
    &:hover,
    &:focus,
    &:active,
    &.active,
    .open .dropdown-toggle#{&} {

I obviously get:

.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.btn-primary .open .dropdown-toggle.btn-primary {
...
}

But I seem not to be allowed to use @at-root:

 .btn-primary {
    ...
    &:hover,
    &:focus,
    &:active,
    &.active,
    @at-root .open .dropdown-toggle#{&} {

Because SASS expects a selector after the comma and gets an @...

like image 377
Johanness Avatar asked Apr 27 '16 23:04

Johanness


People also ask

What is at root?

The @at-root rule is usually written @at-root <selector> { ... } and causes everything within it to be emitted at the root of the document instead of using the normal nesting. It's most often used when doing advanced nesting with the SassScript parent selector and selector functions.

What is the difference between SCSS and sass?

SASS (Syntactically Awesome Style Sheets) is a pre-processor scripting language that will be compiled or interpreted into CSS. SassScript is itself a scripting language whereas SCSS is the main syntax for the SASS which builds on top of the existing CSS syntax.

What is CSS root?

The :root CSS pseudo-class matches the root element of a tree representing the document. In HTML, :root represents the <html> element and is identical to the selector html , except that its specificity is higher.


1 Answers

The @at-root directive cannot be used this way. It is intended to be applied the complete selector, not an individual selector in the list. Since your selectors are both classes, you can just reposition your parent selector to the beginning rather than try to append it to the end:

.btn-primary {
    &:hover,
    &:focus,
    &:active,
    &.active,
    .open &.dropdown-toggle {
      color: red;
    }
}

Output:

.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open .btn-primary.dropdown-toggle {
  color: red;
}

If it absolutely must be at the end (eg. you're using an element or pseudo selector), the simplest solution is to just use extends:

%common {
    color: red;
}

.btn-primary {
    &:hover,
    &:focus,
    &:active,
    &.active {
        @extend %common;
    }

    @at-root .open .dropdown-toggle#{&} {
        @extend %common;
    }
}

Output:

.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary {
  color: red;
}
like image 173
cimmanon Avatar answered Sep 27 '22 18:09

cimmanon