The cart is empty

In recent years, dark mode has become one of the most popular features in digital products and web applications. It allows users to switch between light and dark interface themes, which can improve readability in low-light conditions and reduce energy consumption on devices with OLED displays. This article describes how to implement dark mode on a web page using Cascading Style Sheets (CSS) and user system preferences.

Using Media Queries to Detect User Preferences

The cornerstone of implementing dark mode is the CSS media query prefers-color-scheme. This media query allows websites to query the browser whether the user prefers a light or dark appearance and adjust the page style accordingly.

@media (prefers-color-scheme: dark) {
    /* CSS rules for dark mode */
}

@media (prefers-color-scheme: light) {
    /* CSS rules for light mode */
}

Defining the Color Scheme

When implementing dark mode, it's essential to carefully choose a color scheme that will be comfortable for the eyes in dark environments. Generally, a softer and darker background with more contrasting text should be used.

Example Basic CSS for Dark Mode:

body {
    background-color: #FFFFFF; /* Light background for light mode */
    color: #000000; /* Dark text for light mode */
}

@media (prefers-color-scheme: dark) {
    body {
        background-color: #121212; /* Dark background for dark mode */
        color: #E0E0E0; /* Light text for dark mode */
    }
}

Switching Modes Using JavaScript

For even more flexibility, you can allow users to manually switch between light and dark modes using JavaScript. This can be achieved by toggling classes on the main <body> element and storing the user's preference in localStorage.

 

Implementing dark mode is not just about aesthetics; it's also about user-friendliness and energy efficiency. By using CSS media queries prefers-color-scheme and carefully selecting colors, you can provide users with the option to customize the appearance of your website for their comfort and preferences. Combining CSS and JavaScript allows for even greater control and flexibility when implementing this popular feature.