Vaadin 14 add different styles to elements of the same type?

Viewed 266

I'm trying to figure out how to not apply a blanket style for all of one element using @CssImport. I've searched through the Vaadin docs to no avail.

Currently I'm rendering a MainMenuBar component and a SecondaryMenuBar component below it. I would like for each menu bar to have its own style. In Vaadin 14 I'm not able to attach a class directly on to the MenuItems so I have to target the menu bar buttons in the shadow dom using the @CssImport annotation like so:

@CssImport(value="styles/main-menu-bar.css", themeFor="vaadin-menu-bar-button")

Since I want to do the exact same thing for my SecondaryMenuBar I've add the same themeFor:

@CssImport(value="styles/secondary-menu-bar.css", themeFor="vaadin-menu-bar-button")

As you can imagine, this results in identical styling for both menu bars.

I'm not sure how else to target the menu bar buttons without styling ALL buttons.

Any help would be appreciated.

1 Answers

The preferred way to do this is to utilize theme attributes. It allows you to add additional selector in CSS rule like follows

:host([theme~="secondary-menu"]) ... {
    ...
}

And in Java code you need to set the value of the theme attribute for the component itself.

menuBar.getElement().setAttribute("theme", "secondary-menu");

This theme attribute value is propagated to the sub-components also. Which makes possible for example to style TextField of the ComboBox or DatePicker without styling all the possible TextFields.

Related