7-3 CSS3选择器 :checked选择器
本节编程练习不计算学习进度,请电脑登录imooc.com操作

CSS3选择器 :checked选择器

在表单元素中,单选按钮和复选按钮都具有选中未选中状态。(大家都知道,要覆写这两个按钮默认样式比较困难)。在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;
}

结果演示

任务

在CSS编辑器的第47行输入正确的代码,实现自定义单选按钮的效果。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>属性选择器</title>
  6. <link href="style.css" rel="stylesheet" type="text/css">
  7. </head>
  8. <body>
  9. <form action="#">
  10. <div class="wrapper">
  11. <div class="box">
  12. <input type="radio" checked="checked" id="boy" name="1" /><span></span>
  13. </div>
  14. <label for="boy"></label>
  15. </div>
  16.  
  17. <div class="wrapper">
  18. <div class="box">
  19. <input type="radio" id="girl" name="1" /><span></span>
  20. </div>
  21. <label for="girl"></label>
  22. </div>
  23. </form>
  24. </body>
  25. </html>
  1. form {
  2. border: 1px solid #ccc;
  3. padding: 20px;
  4. width: 300px;
  5. margin: 30px auto;
  6. }
  7. .wrapper {
  8. margin-bottom: 10px;
  9. }
  10. .box {
  11. display: inline-block;
  12. width: 30px;
  13. height: 30px;
  14. margin-right: 10px;
  15. position: relative;
  16. background: orange;
  17. vertical-align: middle;
  18. border-radius: 100%;
  19. }
  20. .box input {
  21. opacity: 0;
  22. position: absolute;
  23. top:0;
  24. left:0;
  25. width: 100%;
  26. height:100%;
  27. z-index:100;/*使input按钮在span的上一层,不加点击区域会出现不灵敏*/
  28. }
  29.  
  30. .box span {
  31. display: block;
  32. width: 10px;
  33. height: 10px;
  34. border-radius: 100%;
  35. position: absolute;
  36. background: #fff;
  37. top: 50%;
  38. left:50%;
  39. margin: -5px 0 0 -5px;
  40. z-index:1;
  41. }
  42.  
  43. input[type="radio"] + span {
  44. opacity: 0;
  45.  
  46. }
  47. input[type="radio"]? + span {
  48. opacity: 1;
  49. }
下一节