Recently, I've noticed that many apps have a dark mode that switches automatically when the system enters dark mode. I later found out that web pages can achieve this effect too, so I spent an afternoon adding a dark mode to this website.
To automatically change colors based on system settings, CSS provides a simple method. In CSS, the @media rule is used for media queries, which allows us to apply different styles based on device characteristics and parameters. The prefers-color-scheme within @media can detect the user's system theme color preference. prefers-color-scheme supports three values: no-preference (no preference), light (light mode), and dark (dark mode).
[!NOTE] According to the MDN documentation,
no-preferenceindicates that the browser's host system does not support theme color settings, or it does but the default is not set or the user has not specified a preference.
First, create a test web page:

Light Mode Example
The CSS part is as follows:
In dark mode, we want to change the text color to white, set the background box to black with transparency, and switch the background image to a darker one while increasing its transparency. To achieve these style changes, you can use the @media (prefers-color-scheme: dark) media query combined with the :root pseudo-class selector, modifying the CSS code as follows:
When the user switches to the system's dark mode, the page's effect will also update automatically.

Dark Mode Example
[!NOTE] Finally, it's important to note that some browsers do not support
prefers-color-scheme. You can see which browsers support it here.