Vaadin-flow: Css stylesheet import for custom components with shadow root element

Viewed 38

I created a server-side component with a shadow-root element.. Is it possible to import a style sheet for the elements within that shadow-root? The CssImport annotation does not work, and I couldn't find anything similar, that could work?!

I could create a static String and add an element, but a css-file-import would be better?! (and of course I could use the component without a shadow-root, but the question was "is it possible" ... )

MyCustomComponent.java

    @Tag("my-custom-component")
    @CssImport("./components/my-custom-component.css")
    public class MyCustomComponent extends Component {
        
        public MyCustomComponent() {
            super();
            ShadowRoot shadow = getElement().attachShadow();

            Span span = new Span();
            span.getElement().setAttribute("part", "caption");

            Div div = new Div();
            div.getElement().setAttribute("part", "content");
            
            shadow.appendChild(span.getElement());
            shadow.appendChild(div.getElement());
        }
    }

my-custom-component.css

:host [part='caption'] {
    background-color: red;
}
:host [part='content'] {
    background-color: blue;
}
1 Answers

I'm curious why you would want a shadow root around a Flow component, as it doesn't really provide any benefits other than CSS encapsulation.

The @CssImport annotation with the themeFor parameter won't help you in this case, as that only works with Web Components using ThemableMixin (https://github.com/vaadin/vaadin-themable-mixin/).

I'm not sure whether it's possible to load css into a shadow root with Flow, but as long as you have part attributes on all elements you want to style, you can do that with a regular (non-shadow-dom) stylesheet, like so:

my-custom-component::part(caption) {
  color: red;
}

Just put that in your styles.css or wherever you have your app's normal global css.

Related