Documentation

Documentation versions (currently viewing)

Run-time Theme Switching Approaches

Implementing multiple sets of styles within a single theme to be loaded dynamically.

Although the application theme cannot exactly be switched at run-time, it is possible to implement multiple distinct sets of styles or variants within a single theme, and to load styles, dynamically.

Multiple Style Sets in a Theme

Similar to how the light and dark variants are implemented in the default Lumo theme, you can combine multiple distinct sets of styles into a single application theme by scoping them with CSS class names that you apply dynamically through application logic. This is known as making custom theme variants.

The most convenient way to approach this is to utilize Lumo style properties, or to define your own custom style properties. However, you can scope any CSS to a particular set or variant by prefixing its selector with the appropriate class name. In the example below, two style sets or variants are implemented in the same application theme, distinguished by the class names forest-theme and fire-theme.

.forest-theme {
  --lumo-primary-color: green;
  --lumo-primary-text-color: darkgreen;
  --brand-color: forestgreen;
}

.fire-theme {
  --lumo-primary-color: orange;
  --lumo-primary-text-color: darkorange;
  --brand-color: orangered;
}

.app-header {
  background-color: var(--brand-color);
}

.fire-theme .app-header {
  Background-image: url('flames.png');
}

Switching between these is done by applying and removing CSS class names from the UI root element like so:

private String currentTheme = "";

private void switchTheme(String newTheme) {

  // Remove the currently applied theme (if any):
  UI.getCurrent().getElement().getClassList().remove(currentTheme);

  // Apply the new theme:
  UI.getCurrent().getElement().getClassList().add(newTheme);
  currentTheme = newTheme;

}

The theme switching method above could be executed based on the user’s domain in a multi-tenant application, calling user preferences stored in a database, or by an event listener on a component that allows the user to choose a theme.

Dark/Light Colors per OS/Browser Settings

Themes with custom dark and light variants can apply them based on the user’s operating system or browser settings. This allows users with dark or light mode set in their system to get the corresponding variant without having to switch to it in the application. This is done through a CSS media query like so:

/* Light scheme applied by default: */
html {
  --UI-background: white;
  --text-color: black;
}

@media(prefers-color-scheme:dark) {
  html {
    --UI-background: black;
    --text-color: white;
  }
}

There’s also a way to apply the built-in Lumo dark theme based on the same OS/browser setting. See OS Light & Dark page.

e6a9898b-960b-468f-a83a-a6dbcba182fa