In this quick tutorial, I’ll show you how to automatically set a dark or light theme in a web application depending on the configuration that the user has in their operating system:

setting light and dark themes

If you prefer, here’s a video version of this tutorial:

Automatic Dark and Light Themes in HTML Documents With CSS

The following steps show how to enable automatic dark and light themes in HTML documents using CSS.

Step1: Create an HTML Document

Create a demo.html file with the following content:

Here’s a screenshot:

hello world dark theme

Step2: Implement a Dark Theme

Add the following to the head section of the demo.html file:

Here’s the result:

Hello world dark theme

Step 3: Use a Media Query to Apply the Dark Theme

Edit the code of the previous step to include the dark styles in a media query that uses a media feature:

Step 4: Test the Spp

Open the HTML document in the browser and use your operating system settings to change the preferred theme. The changes should be automatically reflected in the browser.

Automatic Dark and Light Themes in Web Components and Vaadin Flow Apps

The following steps show how to enable automatic dark and light themes using JavaScript. This is useful if your application uses Web Components that require special configurations or if you are using Vaadin Flow.

Step 1: Create a New Java Web Application With Web Components

Go to https://start.vaadin.com and generate a new application. You can leave all the defaults or tweak it as you wish by adding and removing views or changing the appearance. Follow the instructions and links on the page to import the generated Maven project in your IDE of choice.

Step 2: Implement a Media Query in JavaScript

Create a new os-theme-switcher.js file inside the PROJECT_ROOT/frontend/ directory with the following content:

Step 3: Load the JavaScript File

Add the following annotation to the MainView Java class:

Step 4: Test the App

Run the app with Maven:

Go to http://localhost:8080 and use your operating system settings to change the preferred theme. The changes should be automatically reflected in the browser.



Source link

Write A Comment