2016-07-23 48 views
1

我想創建一個Button。在開始時它沒有邊框,只是背景顏色。所以我設置以下CSS屬性:JavaFX - Button上的左邊框沒有移動文本或調整其大小

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

當按下Button /選擇,左側邊框應該會出現,所以我加了這一點:

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

但問題是,每次顯示邊框時,Button都會變寬一點。

我也嘗試將對齊方式設置爲center-right,並添加最小寬度,但如果Button變大,則不再起作用。它確實不像我想要的那樣。

那麼,沒有這種行爲我該怎麼做?優選地,文本與中心對齊。

回答

2

您可以簡單地使用CSS屬性-fx-background-insets做到這一點:

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

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

enter image description here

特第二選擇創建兩種顏色的兩層。原始背景顏色在左側獲得2像素插圖,因此底層(「邊框」的顏色)將顯示爲左側的2像素邊框。

仔細看看這個選擇器:-fx-background-insets: 0, 0 0 0 2;第一個(底層)背景顏色沒有插入。頂部的顏色在左側有2個像素插入,因爲四個數字表示top, right, bottom, left

注:文本對齊是不必要的,作爲一個Button默認文本對齊或ToggleButton爲中心,但在任何情況下,你可以從CSS也對齊文本:

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

非常感謝你。 – aquaatic