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:
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:
Step2: Implement a Dark Theme
Add the following to the
head section of the demo.html file:
Here’s the result:
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
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.
Create a new os-theme-switcher.js file inside the PROJECT_ROOT/frontend/ directory with the following content:
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.