Sass Selector Functions

Sass Tutorial

Sass Selector Functions

Sass Selector Functions allow you to inspect, combine, and manipulate CSS selectors programmatically.
They are mainly used in advanced Sass, frameworks, utility generators, and mixins.

👉 These functions don’t generate CSS by themselves—they help Sass understand and build selectors.


🔹 What Is a Selector in Sass?

A selector is any CSS selector like:

.button
#header
.nav ul li a

In Sass, selectors can be treated as values and passed to functions.


🔹 Common Sass Selector Functions


1️⃣ selector-nest()

Nests selectors together (like manual nesting).

selector-nest(".card", ".title");

Output:

.card .title

2️⃣ selector-append()

Appends selectors without a space.

selector-append(".btn", "-primary");

Output:

.btn-primary

3️⃣ selector-extend()

Extends one selector with another (advanced @extend behavior).

selector-extend(".btn", ".btn-primary", ".active");

Output:

.btn.active

4️⃣ selector-replace()

Replaces part of a selector.

selector-replace(".btn-primary", ".btn", ".link");

Output:

.link-primary

5️⃣ selector-unify()

Combines selectors if possible.

selector-unify(".btn", ".active");

Output:

.btn.active

(Returns null if not compatible)


6️⃣ selector-parse()

Converts a selector string into selector format.

selector-parse(".nav ul li");

✔ Used internally in advanced logic.


7️⃣ is-superselector()

Checks if one selector matches all elements of another.

is-superselector(".btn", ".btn-primary");

Output:

true

8️⃣ simple-selectors()

Returns simple selectors from a compound selector.

simple-selectors(".btn.active");

Output:

(".btn", ".active")

🔹 Practical Example (Utility Generator)

@mixin state($selector) {
#{selector-nest($selector, "&:hover")} {
color: red;
}
}
.button {
@include state(“.icon”);
}

Output:

.icon .button:hover {
color: red;
}

🔹 Selector Functions vs Nesting

Nesting Selector Functions
Simple & readable Powerful & dynamic
Best for beginners Best for libraries
Static structure Programmatic control

❗ Important Notes

✔ Mostly used in frameworks & advanced mixins
✔ Not common in day-to-day Sass
✔ Requires good selector knowledge
✔ Useful for automation & utilities


📌 Summary

  • Selector functions manipulate CSS selectors

  • Useful for advanced Sass logic

  • Ideal for frameworks & design systems

  • Avoid unless really needed

You may also like...