Search code examples
csssass

how to use :has in sass


I need to add some styles if body has some element with .rtl class. How is possible to do it ?

body:has(.app.rtl) {
   .blah {
       some: blah;
   }
}

This is something that I need


Solution

  • Update 2024: It is now safe to use :has() in the way you attempted to. You can also use nesting in CSS natively now, meaning the rule you provided as an example is now exactly how it works:

    body:has(.app.rtl) {
       .blah {
           some: blah;
       }
    }
    

    enter image description hereenter image description here

    What you want cannot be done using CSS since CSS has no parent selector and currently also no :has selector.

    SASS cannot help you either since all SASS can do for you is make authoring CSS easier - in the end any pre-processor will compile your code to CSS which is the only thing the browser understands. The only cross-browser solution here (still) is Javascript.

    Edit January 2023: As of now, Safari and Chrome/Chromium-based browsers (Edge, Brave, etc.) support :has(), and Firefox has support behind an experimental web platform features flag.

    Your style is going to look like this:

    body:has(.app.rtl) .blah {
        some: blah;
    }