Vaadin: how does @CssImport works among the views? it is a "global" import?

Viewed 66

If I have for example a view where I use

@CssImport(value = "somefile.css")

with somefile.css defined like

.test-foobar {

  color: green

}

I can use .addClassName("test-foobar") in any component in any view/class even if the class is NOT annotated with @CssImport(value = "somefile.css").

It's like that once defined the @CssImport it's global available to all the views.

Other than hard-coding css definition in the class file for every component can you define a css rules in a file that is just imported and used for the view that is annotated with @CssImport ?

P.S. I am using vaadin 14 right now, but it is ok to have informations if it is different in 23+, just to know how it works.

1 Answers

Yes, it's a global import and this is the intended behaviour as stated in the docs

NOTE: Currently all frontend resources are bundled together into one big bundle. This means, that CSS files loaded by one class will be present on a view constructed by another class. For example, if there are two classes RootRoute annotated with @Route(""), and another class RouteA annotated with @Route("route-a") and @CssImport("./styles/custom-style.css"), the custom-style.css will be present on the root route as well.

So from here, it's basically a question, of how drastic you need to change the style between the views.

If it's minute things, on very few components, I'd stick with the global CSS and sprinkle some class names where needed.

If you have massive changes, I'd go for a "sub theme". Create your own theme, and then separate the styling with [theme~="special-theme-for-a"] selectors and setting the theme in your view/router-layout. Ideally you do this by just switching out some vars at very high level. You can take some hints from how light and dark is done in the Lumo theme or how "theme variants" are done for many of the existing components.

Also relevant:

Related