There appears to be a slight issue with the tailwind dark mode not fully extending when scrolling to the bottom of the page

While using dark mode in a Next.js web app with Tailwind, you may have noticed that when scrolling, if you go past the scroll container (almost as if you're bouncing off the bottom or top of the page), the dark mode doesn't extend all the way. Instead, the color isn't applying properly and it shows the previous color underneath (which is usually white). What could be causing this issue and is there a way to ensure that the dark mode extends fully?

Browsers where the issue occurs:

  • Firefox
  • Brave
  • Chrome

Browsers where the dark mode works correctly:

  • Safari

We can see that platforms like Stackoverflow and tailwindcss.com handle dark mode well, extending it fully across the entire page.

_app.tsx

 <Store state={state} dispatch={dispatch}>
        <Head>
          <meta charSet="UTF-8" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0"
          />
        </Head>
        <div className="h-screen dark dark:bg-black dark:text-white overscroll-auto lg:overscroll-contain">
          <Component {...pageProps} id="app" />
        </div>
      </Store>{" "}

Answer №1

Applying styles to the body or :root (HTML) element is essential. In the following examples, I will demonstrate how to apply them to the :root element.

When working with Next.js, you have two main options - using a global stylesheet or inline styling.

For global stylesheet usage with tailwind directives:

Global styles

global.css

@tailwind base;

@layer base {
 :root {
  @apply dark:bg-black dark:text-white;
 }
}

Inline class styling:

To apply styles inline, you need to create a custom _document page. Once again, you can apply styles to either the body or html tags.

_document.js

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

export default function Document() {
  return (
    <Html className="dark:bg-black dark:text-white">
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

Answer №2

Encountering the same issue, I discovered that the problem was due to my styling for dark background/foreground colors being applied to a React component (specifically a container layout component) instead of the body element.

To resolve this, I updated my CSS file to set the dark background/foreground directly on the body element:

@layer base {
  body {
   @apply dark:bg-slate-800 dark:text-white;
  }
}

Additionally, in your pages/_app.jsx file or wherever necessary, you can implement

document.documentElement.classList.add("dark");
to ensure that the dark mode is properly activated even when scrolling.

For more information, refer to: https://tailwindcss.com/docs/dark-mode

Answer №3

After trying numerous solutions without success, I finally found a workaround that did the trick for me. What worked was creating a file called _document.js and adding an id to the HTML section:

_document.js

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

export default function Document() {
    return (
        <Html id="html" className="bg-white">
            <Head />
            <body className="bg-bg-light dark:bg-bg-dark">
                <Main />
                <NextScript />
            </body>
        </Html>
    )
}

Then, during the toggle, add or remove the dark background (without the 'dark:' prefix):

DarkMode.jsx

useEffect(() => {

    if (darkMode !== undefined) {
        if (darkMode) {
            document.body.classList.add("dark");
            document.getElementById("html").classList.add("bg-black")
        } else if (!darkMode) {
            document.body.classList.remove("dark");
            document.getElementById("html").classList.remove("bg-black")
        }
    }
}, [darkMode])

I made sure not to include the tailwind directive in globals.css

Credit goes to Sean W for guiding me in the right direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

This module is not compatible with the "node" engine. It requires a version greater than or equal to 16.0.0, but the current version is 14.18.3 (encountered during deployment on Vercel)

While attempting to deploy my next.js project to Vercel, I encountered the following error. error <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a3e3b2e3b292e35283f772a2f38292f381a68746a746a">[email protected]</a> ...

Issues with navigation functionality in Internet Explorer 8 have been identified in Twitter Bootstrap 3 RC2

I am currently using Twitter Bootstrap 3 RC2 to create a navigation bar at the top of my page, which is working perfectly fine except on IE8. In IE8, it seems like the browser is rendering the page as if it were on a smaller screen, causing the menu to co ...

Utilizing Jquery for toggling HTML elements and styling with CSS

I'm trying to implement a jQuery toggle button that switches between two states below; When I click the Toggle Button/link, everything in picture A (above the red line) should be hidden. Clicking the toggle button again would make it reappear. I&apo ...

Is the URL incorrect if fetching from Firestore URL results in a 404 error?

My current project involves fetching data from my Firestore Database using Next.js. However, I keep encountering an error in the console that reads GET (FirestoreDatabaseURL) 404 (not found). Interestingly, when I attempt to fetch data from other JSON dat ...

What is the best way to resize a primefaces inputTextArea to match the length of the

I am currently working on improving the appearance of <p:inputTextArea/>. When the page loads, I notice: And when I click on that TextArea: Here is the code: <p:inputTextarea rows="6" value="#{bean.object.value}" style="width: 100%;" /> Is ...

Creating a Dual Linear Gradient Background with Tailwind: Step-by-Step Guide

Can you use two linear backgrounds on a single element in Tailwind CSS? I found this CSS code that seems to achieve it: background-image: linear-gradient(to right, #f8fafb 50%, #161616 50%), linear-gradient(to right, #161616 50%, #f8fafb 50%); I att ...

Utilizing next.config.js in Next.js TypeScript for personalized settings

As a newcomer to nextjs typescript, I am currently exploring the usage of next.config.js in my nextjs typescript project for custom configurations. Here is an example of what I have attempted: const path = require('path') module.exports = { sa ...

What could be causing my mdx files to not display basic markdown elements such as lists and headings? (Next.js, mdx-bundler)

Trying to implement Kent C Dodds mdx-bundler with the Next.js typescript blog starter example is proving challenging. While it successfully renders JSX and certain markdown elements, basic markdown syntax like lists and paragraph spacing seem to be malfunc ...

The npm build process encountered an unexpected token error in jsdom

Encountering an error with my next.js app when running "npm run build". The specific error message is as follows: > Build error occurred /var/www/directoryname/node_modules/jsdom/lib/jsdom/browser/parser/html.js:170 after._pushedOnStackOfOpenElement ...

Having issues with mouse hover not functioning on button in internet explorer 8?

Currently, I am working with asp.net mvc4 and encountering an issue where the button's color does not change when hovered over. The default blue focus always remains on the button. Can someone assist me in resolving this problem? I am using Internet E ...

Spaces ahead and beneath the text

I'm struggling to style a small block of text within its element perfectly. Despite my efforts, there always seems to be unnecessary space in front and below the words. One workaround I found was adjusting the line height to remove the bottom gap, but ...

Changing a live request in React

Imagine you have a request that needs to be delayed, similar to how Google Docs waits a moment before sending the "save" request. In browser JavaScript, you could achieve this by implementing code like the following: // Overwrite this global window variabl ...

Is it possible for a navbar in CSS to collapse based on its width?

At the moment, I am utilizing Bootstrap v3.3.6 and jQuery v1.9.1. My current project involves a horizontal navbar that collapses once it reaches a specific screen resolution. I am pleased with how this feature operates and wish to maintain the same breakpo ...

Tips for integrating a vertical menu with button icons and subcategories

Currently working on a project with Twitter Bootstrap and looking to create a specific sidebar setup. My goal is to include subcategories using an accordion and a collapsible menu for mobile devices. I came across a similar implementation at http://jsfiddl ...

Dynamic row addition in Material Design Lite table causes format to break

Here's the HTML markup for creating a checkbox using material-design-lite: <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="checkbox"> <input type="checkbox" id="checkbox" class="mdl-checkbox__input" /> <span c ...

The infinite scroll feature is not functioning properly with the combination of get static props and GraphQL

I've been working on a project involving pokeapi graphql, and I developed an infinite scroll component that dynamically loads more pokemon as you scroll down the page. My goal was to preload the first 48 pokemons using static generation. Here's ...

Tips for keeping the options menu visible even when the video is paused

As I was creating my own customized Video player, I encountered an issue where I wanted the options bar/menu to disappear when the user became inactive. While I have managed to achieve this functionality, I still require the option bar to remain visible ...

Supporting wildcard redirect URLs for Vercel in Asp .Net Identity Server

Currently, I am working with Duende IdentityServer for my back-end RestApi and using Vercel to test the front-end. However, I am facing an issue where I cannot login to IdentityServer with Vercel due to the redirectUrl not being allowed. I have come acros ...

The iteration count and stop code in CSS are failing to function correctly

Is there a way to make this loop once and then stay as is unless the page is refreshed? I've tried multiple methods I came across. Can you modify the code so I can see where the changes are being made? The goal is to have it display once and then per ...

"Within Angular 2+, the attribute referenced is not recognized as a valid property, even though it is explicitly defined within the @Input

The main goal here is to increase the vertical pixel count. <spacer [height]="200"></spacer> Initially facing an issue where an error message states that height is not a recognized attribute of spacer. To address this problem, I set up the fo ...