在日常前端開發中,radio
和 checkbox
是非常常用的表單元素,但瀏覽器預設的樣式往往不符合設計需求。因此,學會如何客製化這些元素樣式是每個前端設計師的必備技能之一。在這篇教學文中,我們將介紹如何使用 CSS 來客製化 radio
和 checkbox
,並將 checkbox
打造為一個開關按鈕 (Switch Button)。
<form>
<label>
<input type="radio" name="option" checked>
選項 1
</label>
<label>
<input type="radio" name="option">
選項 2
</label>
</form>
input[type="radio"] {
display: none; /* 隱藏預設的 radio 按鈕 */
}
label {
position: relative;
padding-left: 25px;
cursor: pointer;
font-size: 16px;
}
label::before {
content: "";
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 16px;
height: 16px;
border: 2px solid #ccc;
border-radius: 50%;
background-color: #fff;
}
input[type="radio"]:checked + label::before {
border-color: #4CAF50;
background-color: #4CAF50;
}
label::after {
content: "";
position: absolute;
left: 6px;
top: 50%;
transform: translateY(-50%);
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #fff;
opacity: 0;
}
input[type="radio"]:checked + label::after {
opacity: 1;
}
使用 display: none
隱藏預設的 radio
按鈕。
使用 label::before
和 label::after
來建立一個自製的圓形按鈕,並且當 radio
被選中時,透過 :checked
伺服器來改變外觀。
<form>
<label>
<input type="checkbox" checked>
選項 A
</label>
<label>
<input type="checkbox">
選項 B
</label>
</form>
input[type="checkbox"] {
display: none; /* 隱藏預設的 checkbox */
}
label {
position: relative;
padding-left: 25px;
cursor: pointer;
font-size: 16px;
}
label::before {
content: "";
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 16px;
height: 16px;
border: 2px solid #ccc;
background-color: #fff;
}
input[type="checkbox"]:checked + label::before {
background-color: #4CAF50;
}
label::after {
content: "✓";
position: absolute;
left: 3px;
top: 50%;
transform: translateY(-50%);
font-size: 12px;
color: white;
opacity: 0;
}
input[type="checkbox"]:checked + label::after {
opacity: 1;
}
使用 display: none
隱藏預設的 checkbox
。
透過 label::before
和 label::after
設計一個自定義的方框,並且當 checkbox
被選中時顯示對勾。
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
.switch {
position: relative;
display: inline-block;
width: 50px;
height: 25px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: 0.4s;
border-radius: 25px;
}
.slider::before {
content: "";
position: absolute;
width: 21px;
height: 21px;
left: 2px;
bottom: 2px;
background-color: white;
transition: 0.4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #4CAF50;
}
input:checked + .slider::before {
transform: translateX(24px);
}
使用 opacity: 0
隱藏預設的 checkbox
。
使用 .slider
來設計開關外觀,當 checkbox
被勾選後,透過 :checked
改變背景色及按鈕位置,達到開關按鈕的效果。
這些自定義的樣式讓我們能夠創建符合設計需求的 radio
、checkbox
及開關按鈕 (Switch Button)。這樣不僅提高了頁面的美觀,也改善了使用者體驗。你可以根據實際專案中的配色方案進行調整,讓你的 UI 元素更加一致。