自定义复选框样式

效果如下

通过label和checkbox,我们可以将checkbox隐藏,而将label制作为各种漂亮超酷的复选框样式。

1.css 如下

  1. #rulelabel{  
  2.     background-image:url(../static/image/unselected.png);  
  3.     background-repeat: no-repeat;  
  4.     background-size: 0.4rem 0.4rem;  
  5.     display: inline-block;  
  6.     height: 0.4rem;  
  7.      0.4rem;  
  8.     position: absolute;  
  9.     top: 0.28rem;  
  10.     left: -0.03rem;  
  11. }  
  12. #agreerule:checked + label{  
  13.     background-image:url(../static/image/selected.png);  
  14. }  
  15. /*将原checkbox宽高设为0,使其不显示*/  
  16. #agreerule{  
  17.      0;  
  18.     height: 0;  
  19.     padding: 0;  
  20.     margin: 0;  
  21. }  
#rulelabel{
    background-image:url(../static/image/unselected.png);
    background-repeat: no-repeat;
    background-size: 0.4rem 0.4rem;
    display: inline-block;
    height: 0.4rem;
     0.4rem;
    position: absolute;
    top: 0.28rem;
    left: -0.03rem;
}
#agreerule:checked + label{
    background-image:url(../static/image/selected.png);
}
/*将原checkbox宽高设为0,使其不显示*/
#agreerule{
     0;
    height: 0;
    padding: 0;
    margin: 0;
}

2.html 如下

  1. <div>  
  2.     <label>  
  3.         <input type="checkbox" name="agreerule" id="agreerule" tabindex="5" checked/>  
  4.         <label id="rulelabel" for="agreerule"></label>  
  5.         同意QQ的服务协议和隐私权声明  
  6.     </label>  
  7. </div>  

涉及的知识点:

兄弟选择器(+ 和 ~)

1. + 选择器

  如果需要选择紧接在另一个元素后的元素,而且二者有相同的父元素,可以使用相邻兄弟选择器。      

比如:

<style type="text/css">
    h1 + p {
        margin-top:50px;
        color:red;
    }
</style>


<body>
<p>This is paragraph.</p>
<h1>This is a heading.</h1>
<p>This is paragraph.</p>
<p>This is paragraph.</p>

  效果:

  这里写图片描述   

可以看出第一个li字体颜色没有变红,第二个和第三个元素字体变红,这就是因为第三个li是第二个li的兄弟元素,所以也会应用样式。

  2. ~ 选择器   作用是查找某一个指定元素的后面的所有兄弟结点。   

示例代码:   

<style type="text/css">
    h1 ~ p{
        color:red;
    }
</style>
</head>
<body>
    <p>1</p>
    <h1>2</h1>
    <p>3</p>
    <p>4</p>
    <p>5</p>
</body>
 
原文地址:https://www.cnblogs.com/liuyanxia/p/6376675.html