Next.js: How to change css of root div __next on specific page?

18,280

Solution 1

One of the workarounds you can do is manually adding a class to #__next on Login Page and then globally style it

import React from 'react';

export default class LoginPage extends React.Component {
  componentDidMount() {
    document.getElementById('__next').classList.add('login-page');
  }

  componentWillUnmount() {
    document.getElementById('__next').classList.remove('login-page');
  }

  render() {
    return (
      <div>
        Login page
        <style jsx global>{`
          .login-page {
            background-color: red;
          }
        `}</style>
      </div>
    );
  }
}

Solution 2

Next.JS' Styled JSX allows you to add a global keyword to your <style> element. Here's how one would customize the __next div.

In your pages/_document.js do this:

// pages/_document.js
import Document, { Head, Main, NextScript } from "next/document";

export default class MyDocument extends Document {
  render() {
    return (
      <html>
        <Head />
        <body>
          <Main />
          <NextScript />
          <style jsx global>{`
            /* Other global styles such as 'html, body' etc... */

            #__next {
              height: 100%;
            }
          `}</style>
        </body>
      </html>
    );
  }
}

Solution 3

Maybe this helps someone.
create a folder "styles" add "globals.css"

add this to that file

@tailwind components;
@tailwind utilities;
@layer components {
    #__next {
        @apply h-full bg-red-500;
    }
    html,
    body {
        @apply h-full;
    }
}

go to your _app.js and import the above stylesheet.
Share:
18,280

Related videos on Youtube

Rukeith
Author by

Rukeith

Updated on July 10, 2022

Comments

  • Rukeith
    Rukeith almost 2 years

    I want to change div which the id is __next on login page. But when I add style in jsx, it seems change to another div with id #__next.jsx-2357705899, .main.jsx-2357705899 while dom mounts to page.

    How could I change css of __next div when login page is mount?

    <style jsx>{`
      #__next,
      .main {
        height: 100%;
      }
    `}</style>
    
  • SkyzohKey
    SkyzohKey over 5 years
    This answer looks on the correct road but it's really an ugly way of doing that. See my answer for a proper solution.
  • Morgan Feeney
    Morgan Feeney over 3 years
    This is the simplest way of dealing with this problem IMO.
  • Muhammad Muzamil
    Muhammad Muzamil over 2 years
    you may edit and give solution for the specific page
  • Ejaz
    Ejaz about 2 years
    Now global style in _document.js does not take effect. Style now has to be applied in _app.js.
  • York Wang
    York Wang almost 2 years
    you sir deserve a medal! thanks for the solution. this is exactly what Ive been searching for!
  • Peter
    Peter almost 2 years
    Just one upvote for the general public.