I took the original CSS file and applied as few as possible changes in order to set up a Dark Mode.
I took the original literal color values (like #000000) and used them to set up a list of initial CSS Variables:
At this point, the site should look exactly the same.
For Dark Mode, we could use the CSS media query prefers-color-scheme.
However, the user might prefer Hacker News in light mode, whilst having his OS in Dark Mode.
Since there is no way to setup a color scheme preference per website, we’ll be using a data attribute on the <html> element:
<html lang="en" op="news" data-theme="dark">
This also makes it easier me to force the Dark Mode for demonstration purposes.
There were also some additional changes I had to make for the Dark Mode to work.
Dark Mode detection
For demonstration purposes, the Dark Mode is forced here by setting a data attribute on the <html> element.
Ideally, this preference would be a user one, and the server would return the appropriate HTML.
It is possible to detect the user’s OS preference in JS:
window.matchMedia("(prefers-color-scheme: dark)").matches; // True if useOS preference is dark
But swapping the theme client-side causes flickering on load, so it should be avoided.
It could however be used to detect a user’s OS preference and set a default value server-side.
Hacker News Dark Mode
Process
I took the original CSS file and applied as few as possible changes in order to set up a Dark Mode. I took the original literal color values (like
#000000) and used them to set up a list of initial CSS Variables:I then set up semantic variables by referencing initial variables:
At this point, the site should look exactly the same.
For Dark Mode, we could use the CSS media query
prefers-color-scheme. However, the user might prefer Hacker News in light mode, whilst having his OS in Dark Mode. Since there is no way to setup a color scheme preference per website, we’ll be using adataattribute on the<html>element:This also makes it easier me to force the Dark Mode for demonstration purposes.
This theme attribute can be targeted with CSS:
There were also some additional changes I had to make for the Dark Mode to work.
Dark Mode detection
For demonstration purposes, the Dark Mode is forced here by setting a
dataattribute on the<html>element. Ideally, this preference would be a user one, and the server would return the appropriate HTML. It is possible to detect the user’s OS preference in JS:But swapping the theme client-side causes flickering on load, so it should be avoided. It could however be used to detect a user’s OS preference and set a default value server-side.