如何使用 CSS 將按鈕元素垂直和水平居中?
要使用 CSS 將按鈕垂直和水平居中,請使用 `justify-content` 和 `align-items` 屬性。在我們的示例中,我們使用了 flex。
justify-content 屬性
在 CSS 中,`justify-content` 屬性用於水平對齊專案。CSS `justify-content` 屬性的語法如下:
Selector { display: flex; justify-content: /*value*/ }
以下是其值:
flex-start - 彈性專案位於容器的起始位置。這是預設值。
flex-end - 彈性專案位於容器的結束位置。
center - 彈性專案位於容器的中心。
space-between - 彈性專案之間會有空間。
space-around - 彈性專案在其之前、之間和之後都會有空間。
space-evenly - 彈性專案周圍會有相等的間距。
align-items 屬性
在 CSS 中,`align-items` 屬性用於設定彈性盒中彈性專案的預設對齊方式。它垂直對齊專案。
CSS `align-items` 屬性的語法如下:
Selector { display: flex; justify-content: /*value*/ }
以下是其值:
stretch - 彈性專案被拉伸以適應容器。
center - 彈性專案位於容器的中心。
flex-start - 彈性專案位於容器的開頭。
flex-end - 彈性專案位於容器的結尾。
建立按鈕
<button> 元素用於在網頁上建立一個按鈕。
<button>This button is centered</button>
設定按鈕樣式:
button{ font-size: 18px; border: none; padding:10px; background-color: darkblue; color:white; }
將按鈕放在 div 內
要使按鈕居中對齊,請將按鈕元素放在 div 內。
<div class="centered"> <button>This button is centered</button> </div>
設定 div 的樣式並居中對齊
要垂直居中對齊,請使用 `align-items` 屬性。要水平居中對齊,請使用 `justify-content` 屬性。將兩個值的屬性都設定為 `center`。
.centered { display: flex; justify-content: center; align-items: center; height: 200px; border: 3px solid rgb(0, 70, 128); }
示例
讓我們來看一個例子:
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .centered { display: flex; justify-content: center; align-items: center; height: 200px; border: 3px solid rgb(0, 70, 128); } button{ font-size: 18px; border: none; padding:10px; background-color: darkblue; color:white; } </style> </head> <body> <h1>Centering Example</h1> <div class="centered"> <button>This button is centered</button> </div> </body> </html>
廣告