Recently I noticed many apps have a dark mode that automatically activates when the system enters dark mode. Later I discovered that web pages can do the same, so I spent an afternoon adding a dark mode to this site.
To make colors change automatically with system settings, CSS offers a concise method. In CSS, the @media rule is used for media queries, letting us apply different styles based on device characteristics and parameters. Under @media, prefers-color-scheme detects the user’s system theme preference. prefers-color-scheme supports three values: no-preference (no preference), light (light mode), and dark (dark mode).
NoteAccording to MDN documentation,
no-preferencemeans the browser’s host system either does not support theme settings, or supports them but has no default or user-specified preference.
First create a test page:

Light mode example
The CSS looks like this
.card{
top: 40%;
margin: auto;
box-shadow: 0px 8px 60px -10px rgba(13,28,39,0.6);
padding: 8px 10px 6px;
background: rgba(255,255,255,.596078431372549);
border-radius: 25px;
position: relative;
text-align: center;
}
p{
color: #000;
font-size: 2em;
}
.bg{
background-image: url(https://cdn.vinking.top/bg.jpg);
position: fixed;
top: 0;
left: 0;
z-index: -1;
width: 100%;
height: 100vh;
background-size: cover;
opacity: .4;
filter: blur(8px);
}
In dark mode, we want to change the text color to white, set the background card to semi-transparent black, swap the background image for a darker one, and increase its opacity. To achieve these style changes, use the @media (prefers-color-scheme: dark) media query together with the :root pseudo-class selector, and update the CSS as follows:
When the user switches the system to dark mode, the page appearance updates automatically.

Dark mode example
NoteFinally, note that some browsers do not support
prefers-color-scheme; you can see which ones here