How to add Tailwind CSS scroll-smooth class to Next.js

Viewed 1875

I want to add scroll behaviour smooth to my Next.js app, and the Tailwind CSS documentation instructs us to add the utility class in <html/>.

    <html class="scroll-smooth ">
      <!-- ... -->
    </html>

This file does not contain an html tag:

  import Head from "next/head";
  import "@material-tailwind/react/tailwind.css";
  import "../styles/globals.css";
 
    function MyApp({ Component, pageProps }) {
      return (
        <>
          <Head>
            <link
              href="https://fonts.googleapis.com/icon?family=Material+Icons"
              rel="stylesheet"
            />
          </Head>
    
            <Component {...pageProps} />
    
        </>
      );
    }
    
    export default MyApp;

How and where can I add the smooth-scroll utility class in my project?

2 Answers

Use a custom _document.js and add it there - Here is an explanation of what it does -

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html class="scroll-smooth">
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

The simplest solution, do it from your globals.css file...

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  html {
    @apply scroll-smooth;
  }
}
Related