0

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;
}
peter
  • 3
  • 2

1 Answers1

0

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.

Rolf
  • 2,178
  • 4
  • 18
  • 29
  • Why not!?! The idea was a select field in combination with another button that opens a dialog. Of course this is also possible without a shadow root, but as you said: "css encapsulation" had been a good opportunity to style that elements without a global scope... – peter Sep 20 '22 at 16:27
  • Well sure, you can still have css encapsulation AND apply css to it with a regular stylesheet using part attributes and the ::part() selector, OR by applying inline styles to the elements through Flow's Style API, e.g. textfield.getStyle().set("color", "red"); – Rolf Sep 23 '22 at 13:15
  • oh and apply the part attribute via Element API e.g. span.getElement().setAttribute("part", "caption"); – Rolf Sep 23 '22 at 13:17