2

I am trying to create custom checkbox using before and images.My code is

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

Css code here

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;
}

But it is appearing only content is present. If I decrease font-size image also decreasing its size. Why?

Lahiru Ashan
  • 602
  • 9
  • 16
Mr.Pandya
  • 1,331
  • 1
  • 10
  • 20

2 Answers2

5

You are trying in wrong way.

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>  
  

Check out this

kapil
  • 341
  • 2
  • 11
  • 1
    The way OP showed also works. because label is associated element to input tag. You can either keep the input inside the label or outside as you shown. – Mr_Green Oct 28 '16 at 05:39
  • Thanks for suggestion nice way. @Mr_green – kapil Oct 28 '16 at 07:26
1

The way you structure the HTML, you don't need to mention for and id attributes to label and input respectively. You need to mention those when the HTML structure is like this:

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

But when you are nesting, they aren't necessary:

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

Here is the code (check the comments):

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>
Mr_Green
  • 36,985
  • 43
  • 143
  • 241