Sass

An ever-growing cheatsheet for Sass. I add things that I think are useful but difficult to unearth or understand.

Contents

  1. Break out of the nesting structure

Break out of the nesting structure

Say you’re applying styles to a nested element like so:

.parent {
    .child {
        opacity: 0;
    }
}

What if you want that .child’s styling to only occur if a ‘grandparent’ of the .parent element has a certain class? Setting styles only when JavasScript is enabled is a good use case: the root html tag sometimes has the .js class applied to it.

So how do I apply that child style only if that html tag—all the way up the tree—has that .js class? Sass makes this easy with the @at-root rule.

@at-root .js {
    .parent {
        .child {
            opacity: 0;
        }
    }
}

You can use the @at-root rule even when nested. It essentially ‘breaks out’ of your nesting structure.

.great-grandparent {
    .grandparent {
        @at-root .js {
            .parent {
                .child {
                    opacity: 0;
                }
            }
        }
    }
}

Source