Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Dark-mode aware scrollbars using CSS

I have created a little web app called Notepad which is also a progressive web app (PWA). It’s a minimal notepad app where you can quickly jot down stuff that gets saved in the browser’s localStorage.

Now, the app also comes with a dark mode which can be toggled right from the header. Here’s what the app looked like in the dark mode.

Notepad dark mode

This looks nice, right? But one thing you might have noticed in the screenshot is the scrollbar there looks kind of odd because the white scrollbar pops out from the dark background.

That is because when the dark mode is toggled, we are not tinkering around with the default scrollbar color (i.e white).

So, to make it look more in blend with the dark mode, we can make the scrollbar darkmode-aware. And turns out, it’s pretty simple to do with the color-scheme CSS property.

Here’s how it works.

When the user toggles the dark mode, a dark class would apply to the body. All we need to do is add the color-scheme property to this class and set it to “dark” like so.

.dark {
  background-color: #0d1117;
  color-scheme: dark;
}

The color-scheme CSS property allows an element to indicate which color schemes it can comfortably be rendered in. The browser will try to adjust the color of some of the elements based on this preference.

So, when we set it to “dark”, the browser will render the scrollbars in a dark-ish color like so.

Notepad dark scrollbar

As you can tell, even though it’s a subtle change, things look much more cohesive than previously!

Check transition of the scrollbar on toggling the dark mode.

In my opinion, this is a pretty simple fix that should be implemented by all the websites which offer a dark mode (I’m looking at you Twitter!).

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?