Docs

Documentation versions (currently viewingVaadin 25 (prerelease))

Loading Stylesheets Dynamically

Explains how dynamically to load stylesheets.

Stylesheets can be loaded dynamically based on application logic on the server side. This can be useful, for example, to load styles based on the current user, or to allow the user to switch between different themes, manually.

This is done using the addStyleSheet method on the Page class, which takes a URL parameter. The URL can point either to a stylesheet served by the application itself, located in the resource folder src/main/resources/META-INF/resources, or to an external URL.

Source code
Java
/* Local style sheet served by the application */
/* Located in src/main/resources/META-INF/resources/dynamic-styles.css */
UI.getCurrent().getPage().addStyleSheet("dynamic-styles.css");
/* Style sheet loaded from an external URL */
UI.getCurrent().getPage().addStyleSheet("https://example.com/styles.css");

Files loaded this way are applied to the entire UI in the current session, and remain applied until the end of the session.

Dynamic stylesheets can be removed using the Registration instance returned by the addStyleSheet method.

Source code
Java
/* Add dynamic stylesheet */
Registration registration = UI.getCurrent().getPage().addStyleSheet("dynamic-styles.css");
/* Remove dynamic stylesheet when it is not needed anymore */
registration.remove();

6c72d9f9-16d5-4ab5-add8-3c481c3103f8