1. 程式人生 > >CSS3選擇器:屬性、:root、:not、:empty、:target、first-child、last-child....

CSS3選擇器:屬性、:root、:not、:empty、:target、first-child、last-child....

在表單元素中,單選按鈕和複選按鈕都具有選中未選中狀態。(大家都知道,要覆寫這兩個按鈕預設樣式比較困難)。在CSS3中,我們可以通過狀態選擇器“:checked”配合其他標籤實現自定義樣式。而“:checked”表示的是選中狀態。

示例演示:

通過“:checked”狀態來自定義複選框效果。

HTML程式碼

<form action="#">
  <div class="wrapper">
    <div class="box">
      <input type="checkbox" checked="checked" id="usename" /><span>√</span>
    </div>
    <lable for="usename">我是選中狀態</lable>
  </div>
  
  <div class="wrapper">
    <div class="box">
      <input type="checkbox"  id="usepwd" /><span>√</span>
    </div>
    <label for="usepwd">我是未選中狀態</label>
  </div>
</form> 

CSS程式碼:

form {
  border: 1px solid #ccc;
  padding: 20px;
  width: 300px;
  margin: 30px auto;
}

.wrapper {
  margin-bottom: 10px;
}

.box {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 10px;
  position: relative;
  border: 2px solid orange;
  vertical-align: middle;
}

.box input {
  opacity: 0;
  position: absolute;
  top:0;
  left:0;
}

.box span {
  position: absolute;
  top: -10px;
  right: 3px;
  font-size: 30px;
  font-weight: bold;
  font-family: Arial;
  -webkit-transform: rotate(30deg);
  transform: rotate(30deg);
  color: orange;
}

input[type="checkbox"] + span {
  opacity: 0;
}

input[type="checkbox"]:checked
+ span { opacity: 1; }

結果演示