aquaatic aquaatic - 4 months ago 29
CSS Question

JavaFX - left border on Button without moving its text or resizing it

I want to create a

Button
. At the start it has no border, just a background-color. So I set the following CSS attributes:

.button, .toggle-button {
-fx-background-color: #373e48;
-fx-background-radius: 0;
}


When the
Button
is pressed / selected, a border on the left side should appear, so I added this:

.button:pressed, .toggle-button:selected {
-fx-border-color: #ee543a;
-fx-border-width: 0 0 0 2px;
}


The problem with that is that everytime the border is shown, the
Button
gets a little bit wider.

I also tried to set the alignment to
center-right
and add a minimum width, but if the
Button
gets bigger, it doesn't work anymore like that. And it does actually not look like I want it to.

So, how can I do that without this behavior? Preferably with the text aligned to the center.

Answer

You can do this simply in CSS using -fx-background-insets property:

.button, .toggle-button {
  -fx-background-color: #373e48;
  -fx-background-radius: 0;
}

.button:pressed, .toggle-button:selected {
  -fx-background-color: #ee543a, #373e48;
  -fx-background-insets: 0.0, 0.0 0.0 0.0 2.0;
}

Te second block puts the two colors as two layers to each other and the original background color gets a 2 pixel inset on the left side, therefor the underlying color will be shown as a 2 pixel border on the left.

The default text alignment for a Button or a ToggleButton is center, but in any case you can align the text also from CSS:

.button, .toggle-button {
    -fx-text-alignment: center; //* or left, right, justify  *//
}