How To Detect The OS Dark/Light Mode In HTML

Here, we will learn about how to detect the browser themes like the theme is white or dark.

The dark themes have become more and more popular now a days, and more apps and websites start to provide a dark version of their interface. Some offer an option to switch between the versions but it is also possible to detect the theme using CSS. In this article, We will learn how to use these. so let’s start

Detecting theme in CSS

To detect a dark theme in CSS we used the prefers-color-scheme media feature. Using it we can target the light or dark themes that the user has selected for their operating system.

/* Light mode */
@media (prefers-color-scheme: light) {
    body {
        background-color: white;
        color: black;
    }
}

/* Dark mode */
@media (prefers-color-scheme: dark) {
    body {
        background-color: black;
        color: white;
    }
}

light indicates the user has expressed the preference for a page that has a light theme (dark text on light background)

dark indicates the user has expressed the preference for a page that has a dark theme (light text on dark background).

<html>
<head>
    <meta name="color-scheme" content="light dark">
    <meta name="supported-color-schemes" content="light dark">
    <style>
        /* Light mode */
        @media (prefers-color-scheme: light) {
            body {
                background-color: white;
                color: black;
            }
        }

        /* Dark mode */
        @media (prefers-color-scheme: dark) {
            body {
                background-color: black;
                color: white;
            }
        }
    </style>
</head>
<body>
    <h1> The Code Hubs </h1>
</body>
</html>

The browser will use this information with the user’s browser or device settings to determine what colors to use for everything from background and foregrounds to form controls and scrollbars. The primary use for <meta name=”color-scheme”> is to indicate compatibility with the order of preference for light and dark color modes.

I hope this article helps you and you will like it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories