【问题标题】:Checkbox using images,:before tag [duplicate]使用图像的复选框,:标签前[重复]
【发布时间】:2017-03-10 22:47:03
【问题描述】:

我正在尝试使用之前和图像创建自定义复选框。我的代码是

<label for="gbx">
    <input type="checkbox" name="gbx" id="gbx">
    <span>12344</span>
</label>

这里是css代码

input {
    display: none;
}

span:before{
    content: "s";
    display: block;
    background-image: url("3_.png");
    background-repeat: no-repeat;
    width: 20px;
    background-size: cover;
}

input:checked+ span:before{
    content: "vijay";
    display: block;
    background-image: url("2_.png");
    background-repeat: no-repeat;
    width: 20px;
    background-size: cover;
}

但它似乎只存在内容。如果我减小字体大小的图像也会减小它的大小。为什么?

【问题讨论】:

    标签: html css


    【解决方案1】:

    你在尝试错误的方式。

    input[type="checkbox"] {visibility:hidden;}
    div label:before {content:'';width:10px;height:10px;background:#fff;border:1px solid red; display:inline-block;margin-right:10px;}
    div input[type="checkbox"]:checked ~ label:before{background:red;}
    
    .new span:before{content:'';width:10px;height:10px;background:#fff;border:1px solid green; display:inline-block;margin-right:10px;}
    .new input[type="checkbox"]:checked ~ span:before {background:green;}
    <div>
      <input type="checkbox" id="working" >
      <label for="working" >For my checkbox</label>
    </div>
    
    
    
    <label class="new">
      <input type="checkbox">
      <span>2nd way</span>
    </label>  
      

    看看这个

    【讨论】:

    • OP 显示的方式也有效。因为标签是与输入标签相关联的元素。您可以将输入保持在标签内部或外部,如图所示。
    • 感谢您的建议。 @Mr_green
    【解决方案2】:

    根据您构建 HTML 的方式,您无需分别为 labelinput 提及 forid 属性。当 HTML 结构如下时,您需要提及:

    <label for="gbx"></label>
    <input type="checkbox" id="gbx"></input>
    

    但是当你嵌套时,它们不是必需的:

    <label>
        <input type="checkbox"></input>
    </label>
    

    这是代码(检查 cmets):

    input {
      /* don't use display: none */
      position: absolute;
      visibility: hidden;
      z-index: -1;
    }
    span:before {   
      content: "";
      display: inline-block;
      vertical-align: baseline;
      width: 10px;
      height: 10px;
      border: 1px solid black;
    }
    :checked + span:before {
      /* no need of mentioning content here again as you alread did in the above code */
      background-color: skyblue;
    }
    <label>
      <input type="checkbox" name="gbx">
      <span>12344</span>
    </label>

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 2016-04-20
      • 2016-04-27
      • 1970-01-01
      • 2015-03-20
      • 2013-12-31
      相关资源
      最近更新 更多