JavaFX: Applying CSS styles to individual elements

This entry is part 44 of 55 in the series JavaFX

We can choose to apply styling to only individual element or control.  We can also apply CSS styling to layout control such as HBox.

We will use the following CSS style sheet to apply some formatting to the Hbox and Label.

.hbox {
    -fx-background-color: lightblue;
    -fx-padding: 20;
    -fx-spacing: 10;

.label {
    -fx-font-size: 12pt;
    -fx-font-family: "Cambrias";

So now we do not have to use statement such as below to control the padding of the HBox.

hbox.setPadding(new Insets(10, 10, 10, 10));

Here is the full example.

package javafxapplication23;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.layout.Priority;

public class JavaFXApplication23 extends Application {

    public void start(Stage stage) {

        stage.setTitle("JavaFX Program!");

        HBox hbox = new HBox(10); // spacing = 10  

        Label lb = new Label("Send Us:");
        Button button = new Button("Submit");
        hbox.setHgrow(button, Priority.ALWAYS);

        hbox.getChildren().addAll(lb, button);

        Scene scene = new Scene(hbox, 300, 250);

    public static void main(String[] args) {


Series Navigation<< JavaFX: Applying CSS style to a scene
JavaFX: Inline statement and CSS ID >>

Leave a comment

Leave a Reply