🎨 自定義 Checkbox 顏色完整指南
方法一:使用 accent-color 屬性(推薦)
這是最簡單的方法,適用於現代瀏覽器(Chrome 93+, Firefox 92+, Safari 15.4+)
CSS 程式碼:
/* 使用 accent-color 屬性 */
.custom-checkbox {
accent-color: #ff4757; /* 設定你想要的顏色 */
width: 20px;
height: 20px;
}
/* 不同顏色範例 */
.red-checkbox { accent-color: #ff4757; }
.green-checkbox { accent-color: #2ed573; }
.blue-checkbox { accent-color: #3742fa; }
方法二:完全自定義樣式
隱藏原生 checkbox,使用自定義元素。相容性最好,可完全控制外觀。
HTML 結構:
<label class="custom-checkbox">
<input type="checkbox">
<span class="checkmark"></span>
<span>選項文字</span>
</label>
CSS 樣式:
/* 隱藏原生 checkbox */
.custom-checkbox input[type="checkbox"] {
opacity: 0;
position: absolute;
width: 0;
height: 0;
}
/* 自定義 checkbox 外觀 */
.custom-checkbox .checkmark {
position: relative;
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid #ddd;
border-radius: 3px;
background-color: white;
cursor: pointer;
transition: all 0.3s ease;
}
/* 選中狀態的樣式 */
.custom-checkbox input[type="checkbox"]:checked + .checkmark {
background-color: #ff6b6b; /* 你想要的顏色 */
border-color: #ff6b6b;
}
/* 勾選符號 */
.custom-checkbox .checkmark:after {
content: "";
position: absolute;
display: none;
left: 6px;
top: 2px;
width: 6px;
height: 12px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
.custom-checkbox input[type="checkbox"]:checked + .checkmark:after {
display: block;
}
方法三:圓形 Checkbox
創建圓形的 checkbox 樣式,適合特殊設計需求。
圓形 Checkbox CSS:
/* 圓形 checkbox */
.round-checkbox .round-checkmark {
border-radius: 50%; /* 設定為圓形 */
/* 其他樣式與方形相同 */
}
方法四:使用 CSS Filter(實驗性)
使用 CSS filter 屬性改變顏色,但效果可能因瀏覽器而異。
Filter CSS:
/* 使用 filter 改變顏色 */
.filter-red {
filter: hue-rotate(0deg) saturate(2);
}
.filter-green {
filter: hue-rotate(120deg) saturate(2);
}
.filter-blue {
filter: hue-rotate(240deg) saturate(2);
}
💡 建議:
- 現代專案:優先使用
accent-color 屬性,簡單且效果好
- 需要完全控制:使用完全自定義樣式方法
- 舊瀏覽器支援:使用自定義樣式方法,相容性最好
- 特殊設計:可以結合多種方法創造獨特效果
瀏覽器支援度
- accent-color:Chrome 93+, Firefox 92+, Safari 15.4+
- 自定義樣式:所有現代瀏覽器
- CSS Filter:大部分現代瀏覽器,但效果可能不一致