如何創建:自定義復選框
學習如何使用 CSS 創建自定義復選框和單選按鈕。
默認:
OneTwo
One
Two
自定義復選框:
自定義單選按鈕:
如何創建自定義復選框
第一步 - 添加 HTML:
<label class="container">One <input type="checkbox" checked="checked"> <span class="checkmark"></span> </label> <label class="container">Two <input type="checkbox"> <span class="checkmark"></span> </label> <label class="container">Three <input type="checkbox"> <span class="checkmark"></span> </label> <label class="container">Four <input type="checkbox"> <span class="checkmark"></span> </label>
第二步 - 添加 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; }