Search code examples
javacssjavafxfxml

In javafx apply css styles to only the top-level menus but not their sub-menus


In a javafx proj with fxml & css files for ui design & styling, naturally there is a MenuBar containing a menu-tree like:

Edit
  |
  Copy
  Paste

View
  |
  ShowGrid
  Show
  Zoom
    |
    50%
    100%

Here Edit & View are top-level menus and Zoom is a submenu.

I want to style the top-level Menus so in the css file I add things like:

.menu {
    -fx-pref-height: 36;
    -fx-background-radius: 4;
}

But it would also apply to the submenu Zoom. Is there a way to distinguish them?

That is, to distinguish Menu objs directly under a MenuBar and those under some other Menu obj.

True that I could just use the fx:id and repeat the style body:

#menuEdit {
    -fx-pref-height: 36;
    -fx-background-radius: 4;
}
#menuView {
    -fx-pref-height: 36;
    -fx-background-radius: 4;
}

But that seems very ineffient and error-prone.


Solution

  • Solution 1:

    Try to use this CSS:

    .menu-bar .container > .menu {
        -fx-pref-height: 36;
        -fx-background-radius: 4;
    }
    

    This CSS styles only the direct child menus of all menuBars. If you want to only style the direct menus of a single menuBar, you can use #menuBarId .container > .menu { ... }.

    Solution 2:

    You could try #menuEdit, #menuView{...}. The CSS equivalent you need is "not", but this is not implemented in JavaFx CSS.