原生 <input type="checkbox"> 無法通過 CSS 修改邊框顏色。瀏覽器對原生表單控件渲染封裝極深,border、background、appearance 等樣式在大多數瀏覽器中無效或表現不一。
/* 嘗試修改原生 checkbox 邊框 - 無效 */
input[type="checkbox"] {
border: 2px solid red; /* 無效 */
border-radius: 4px; /* 無效 */
width: 20px; height: 20px; /* 僅影響佈局盒子,不改變勾選框外觀 */
}
$('input').iCheck({checkboxClass: 'icheckbox_square-blue'}),純 CSS 主題,無圖片。$('[data-toggle="toggle"]').bootstrapToggle()。
/* 隱藏原生 checkbox */
.custom-checkbox input[type="checkbox"] {
position: absolute;
opacity: 0;
width: 0; height: 0;
}
/* 構建自定義框 */
.custom-checkbox .checkmark {
display: inline-block;
width: 20px; height: 20px;
border: 2px solid #ccc; /* 可控邊框顏色 */
border-radius: 4px;
position: relative;
cursor: pointer;
transition: border-color 0.2s;
}
/* 勾選狀態 */
.custom-checkbox input:checked + .checkmark::after {
content: "";
position: absolute;
left: 7px; top: 3px;
width: 5px; height: 10px;
border: solid #2196F3;
border-width: 0 3px 3px 0;
transform: rotate(45deg);
}
/* Hover/Focus 狀態 */
.custom-checkbox input:hover + .checkmark { border-color: #2196F3; }
.custom-checkbox input:focus + .checkmark { box-shadow: 0 0 0 2px rgba(33,150,243,0.2); }
<label class="custom-checkbox">
<input type="checkbox" />
<span class="checkmark"></span>
同意條款
</label>
.custom-checkbox input:checked + .icon::before { content: "\e900"; color: #2196F3; } /* 勾選圖標 */
.custom-checkbox input + .icon::before { content: "\e901"; color: #999; } /* 未勾選圖標 */
| 場景 | 推薦方案 |
|---|---|
| 項目已用組件庫 | 直接用組件庫 Checkbox |
| 輕量頁面、無構建工具 | CSS 偽元素模擬 |
| 需複雜動畫/無障礙支持 | iCheck / 組件庫 |
放棄修改原生 Checkbox 邊框,擁抱「隱藏原生 + 模擬 UI」模式,是前端開發的標準最佳實踐。