Samuel Kosasih
Samuel Kosasih

Reputation: 35

Set CSS styling to a specific elements in JavaFX

I am trying to design myself a UI in JavaFX as part of my learning process. I'm trying to use CSS to make things much easier, but I can't really grasp its concept.

What I have is a BorderPane with a ToolBar in the top position, and a GridPane in the center position.

My question is, how do I set styles to a group specific elements only. For example, I'm trying to set a style only specific to Label elements inside my ToolBar. I have a whole bunch of Labels in my window, but I'm only trying to style those inside my ToolBar. Is that possible?
I tried adding this code in my stylesheet:

.tool-bar label {
    -fx-font-family: Arial;
    -fx-font-size: 15pt;
}

But apparently, it doesn't style any of the Labels at all.

Thanks in advance.

Edit: Rephrased the question, since I meant that I'm targeting a group of specific nodes. Thank you to those who answered already though.

Upvotes: 1

Views: 2880

Answers (1)

Miss Chanandler Bong
Miss Chanandler Bong

Reputation: 4258

From the JavaFX CSS Reference:

Each node in the scene graph has an id variable, a string. This is analogous to the id="..." attribute that can appear HTML elements. Supplying a string for a node's id variable causes style properties for this node to be looked up using that id. Styles for specific ids can be specified using the "#nodeid" selector syntax in a style sheet.

Example:

label.setId("customlabel");

CSS File:

#customlabel {
    -fx-font-family: Arial;
    -fx-font-size: 15pt;
}

To apply the same style for different nodes, you can use style classes:

Each node in the scene graph has a styleClass variable, a List. This is analogous to the class="..." attribute that can appear on HTML elements. Supplying a string for a node's styleClass variable causes style properties for that style class to applied to this node. Styles for style classes can be specified using the ".styleclass" selector syntax in a style sheet. Note that a node may have more than one style class.

node.getStyleClass().add("custom-content");

CSS File:

.custom-content {
    -fx-font-family: Arial;
    -fx-font-size: 15pt;
}

Upvotes: 1

Related Questions