如何 - 自定義複選框
學習如何使用 CSS 建立自定義複選框和單選按鈕。
預設值
一個兩個
一個
兩個
自定義複選框
自定義單選按鈕
如何建立自定義複選框
步驟 1) 新增 HTML
示例
<label class="container">一個
<input type="checkbox" checked="checked">
<span class="checkmark"></span>
</label>
<label class="container">兩個
<input type="checkbox">
<span class="checkmark"></span>
</label>
<label class="container">三個
<input type="checkbox">
<span class="checkmark"></span>
</label>
<label class="container">四個
<input type="checkbox">
<span class="checkmark"></span>
</label>
步驟 2) 新增 CSS
示例
/* 自定義標籤(容器) */
.container {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* 隱藏瀏覽器預設的複選框 */
.container input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
/* 建立自定義複選框 */
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
}
/* 滑鼠懸停時,新增灰色背景色 */
.container:hover input ~ .checkmark {
background-color: #ccc;
}
/* 當複選框被選中時,新增藍色背景 */
.container input:checked ~ .checkmark {
background-color: #2196F3;
}
/* 建立複選標記/指示器(未選中時隱藏) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* 選中時顯示覆選標記 */
.container input:checked ~ .checkmark:after {
display: block;
}
/* 樣式化複選標記/指示器 */
.container .checkmark:after {
left: 9px;
top: 5px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
自己動手試一試 »
如何建立自定義單選按鈕
示例
/* 自定義標籤(容器) */
.container {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* 隱藏瀏覽器預設的單選按鈕 */
.container input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
/* 建立自定義單選按鈕 */
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
border-radius: 50%;
}
/* 滑鼠懸停時,新增灰色背景色 */
.container:hover input ~ .checkmark {
background-color: #ccc;
}
/* 當單選按鈕被選中時,新增藍色背景 */
.container input:checked ~ .checkmark {
background-color: #2196F3;
}
/* 建立指示器(點/圓 - 未選中時隱藏) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* 選中時顯示指示器(點/圓) */
.container input:checked ~ .checkmark:after {
display: block;
}
/* 樣式化指示器(點/圓) */
.container .checkmark:after {
top: 9px;
left: 9px;
width: 8px;
height: 8px;
border-radius: 50%;
background: white;
}
自己動手試一試 »