CSS Modules in Nextjs: Target Html Tag from Local CSS File?

Viewed 26

I want to apply smooth scrolling only to a very specific page in nextjs (say my blog). So I am not using my globals.css file, but I need a way to inject scroll-behavior: smooth; into the html tag for specific pages only, not for my whole site.

I believe that there is a way to do this with css modules, but I do not understand how it works. Here is explained how this would work with css classes, but I don't understand how this would look like for my use case, where I try to target the html tag?

Any advice?

I tried this:

.foo :global {
  html {
    scroll-behavior: smooth;
  }
}

and this:

html :global {
  .foo {
    scroll-behavior: smooth;
  }
}

But I get:

Syntax error: Selector "html :global" is not pure (pure selectors must contain at least one local class or id)

1 Answers

I found this package called Styled JSX which does exactly what you are looking for.

From this Vercel blogpost:

Styled JSX is a CSS-in-JS library that allows you to write encapsulated and scoped CSS to style your components. The styles you introduce for one component won't affect other components, allowing you to add, change and delete styles without worrying about unintended side effects.

Moreover, Styled JSX is a built-in feature of NextJS, so you can use it out-of-the-box!

Next.js includes Styled JSX by default, so getting started is as simple as adding a <style jsx> tag into an existing React element and writing CSS inside of it

You could use it like this in your case:

function BlogPage() {
  return (
    <div className="container">
      <h1>Blog post example</h1>
      <p>Hi! Welcome to my blogpost!</p>
      <style jsx>{`
        html {
          scroll-behavior: smooth;
        }
      `}</style>
    </div>
  );
}
Related