HTML

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.

Jignesh Patel

Jignesh Patel is a Senior Full Stack .Net Developer has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET MVC, AngularJS, Angular, Nodejs, Web API, EPPlus, SQL, Entity Framework, JavaScript, Azure Web Jobs, Microsoft Graph API, etc.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago