My use case is changing look and feel, such as primary color, and may be other color depending on the user preferences. One way would be set the colors every time a component is created, but that seems to be not every efficient. Is there a way to add a “dynamic” CSS resource that would be generated out of the data source and overwrite whatever the default values?
Depends on how “dynamic” your “dynamic” is - if we are talking about 3-4 different presets, I would go with different theme variants (like light/dark mode) and apply those different colorings default in your styles.css and just swap your application variant based on the user setting.
It is completely dynamic. The app doesn’t know what it is at the build time.
I’m thinking, it may be possible to create a servlet that responds to <context>/styles/dynamic.css
with style overrides. The question is, how to add the reference to /styles/dynamic.css
to a view?
Thanks! Let’s me give it a try.
The docs say “Note that files loaded this way are applied to the entire UI in the current session, and remain applied until the end of the session.” It would make sense to do it only once, then. What’s the best way to call UI.getCurrent().getPage().addStyleSheet("dynamic-styles.css");
once per session?
/* Local style sheet (served by the application) */
UI.getCurrent().getPage().addStyleSheet("dynamic-styles.css");
What is the difference between using UI.getCurrent().getPage().addStylesheet("...");
and
@StyleSheet("lazy-loaded.css")
public class MyUI extends Div {
…
}
The annotation is discouraged - Styling Components | Styling | Vaadin Docs
So, so far my hope of using si not materializing. According to CSS Loading Order | Advanced Topics | Flow | Vaadin Docs, stylesheets added by UI.getCurrent().getPage().addStylesheet(“…”) are added before the theme stylesheet is loaded, thus not allowing to override anything. Is there a way to change the load order and load those after the theme stylesheets?
That’s not possible; you would need selectors with higher precedence
Understood. I solved it by using var(…, ) in the theme CSS. This is not perfect because it breaks the cascading part of the CSS, but hey, it works.
I’m curios, addStylesheet(…) coming before the the theme, is it a design choice, or is it a technology limitation?
From my understanding it’s by design… I had a similar “problem” in the past. Normally @Stylesheet and addStyleSheet are used by add-ons; theme comes last to allow you to easily fix “externally” provided css