CSS 按鈕
學習如何使用 CSS 設置按鈕樣式。
基本按鈕樣式
實例
.button { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; }
按鈕顏色
請使用 background-color
屬性更改按鈕的背景色:
實例
.button1 {background-color: #4CAF50;} /* 綠色 */ .button2 {background-color: #008CBA;} /* 藍色 */ .button3 {background-color: #f44336;} /* 紅色 */ .button4 {background-color: #e7e7e7; color: black;} /* 灰色 */ .button5 {background-color: #555555;} /* 黑色 */
按鈕尺寸
請使用 font-size
屬性更改按鈕的字體大小:
實例
.button1 {font-size: 10px;} .button2 {font-size: 12px;} .button3 {font-size: 16px;} .button4 {font-size: 20px;} .button5 {font-size: 24px;}
請使用 padding
屬性更改按鈕的內邊距:
實例
.button1 {padding: 10px 24px;} .button2 {padding: 12px 28px;} .button3 {padding: 14px 40px;} .button4 {padding: 32px 16px;} .button5 {padding: 16px;}
圓角按鈕
請使用 border-radius
屬性為按鈕添加圓角:
實例
.button1 {border-radius: 2px;} .button2 {border-radius: 4px;} .button3 {border-radius: 8px;} .button4 {border-radius: 12px;} .button5 {border-radius: 50%;}
彩色的按鈕邊框
請使用 border
屬性為按鈕添加彩色邊框:
實例
.button1 { background-color: white; color: black; border: 2px solid #4CAF50; /* 綠色 */ } ...
可懸停按鈕
當鼠標移動到按鈕上方時,使用 :hover
選擇器可更改按鈕的樣式。
提示:請使用 transition-duration
屬性來確定“懸停”效果的速度:
實例
.button { transition-duration: 0.4s; } .button:hover { background-color: #4CAF50; /* Green */ color: white; } ...
陰影按鈕
請使用 box-shadow
屬性為按鈕添加陰影:
實例
.button1 { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19); } .button2:hover { box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19); }
禁用的按鈕
請使用 opacity
屬性為按鈕添加透明度(創建“禁用”外觀)。
提示:您還可以添加帶有 "not-allowed" 值的 cursor
屬性,當您將鼠標懸停在按鈕上時,該屬性會顯示 "no parking sign"(禁停標志):
實例
.disabled { opacity: 0.6; cursor: not-allowed; }
按鈕寬度
默認情況下,按鈕的大小取決于其文本內容(與內容的寬度一樣)。請使用 width
屬性來更改按鈕的寬度:
實例
.button1 {width: 250px;} .button2 {width: 50%;} .button3 {width: 100%;}