Search code examples
cssreactjsnext.jssassnext.js13

Styles not being applied while using .modules.scss in Next.js


I've started a Next.js 13 app,

I have a main.modules.scss file

.heading {
    font-size: 4rem;
    color: #000;
}

.dark .heading {
    color: #fff;
}

I am using it to style a component like this

import styles from "@/styles/main.module.scss";

export default function Home() {
    return (
        <>
            <Header />
            <h1 className={styles["heading"]}>Hi! I was styled by scss</h1>
        </>
    );
}

The styles from the .heading class are getting applied properly, but the properties from .dark .heading are not.

My theme provider does add a .dark class to the HTML element.

I used a plain .scss file and applied a class something like this

    <h1 className="heading">Hi! I was styled by scss</h1>

Then it worked perfectly fine


Solution

  • You can use :global to state that you are using a global class

    so your main.modules.scss will become

    .heading {
        font-size: 4rem;
        color: #000;
    }
    
    :global(.dark) .heading {
        color: #fff;
    }
    
    

    Why does this work?

    Warning: I am not a CSS expert

    CSS modules are scoped to component they are used in.

    This mean by default the .dark selector gets transpiled and does not refer to the global .dark class.

    • Check out this post for a more info about CSS modules
    • Check this blog post for more info about the use of :global