soma56 soma56 - 1 month ago 17
CSS Question

How to Create Different Styles for input[type=checkbox]?

This response does an excellent job of showing you how to style checkboxes on a page: Checkboxes not working

…albeit input[type=checkbox] applies its styling on all checkboxes.

I’d like to incorporate images for two different checkboxes – we’ll say facebook and twitter respectively. As a result I’ll need to style them independently because they both have different images and also different images when clicked upon.

With the code below it works perfectly fine for the first checkbox.

Style:

input[type=checkbox] {
display:none;
}

input[type=checkbox] + label
{
background-image:url(facebook_active.png);
height: 53px;
width: 77px;
display:inline-block;
padding: 0 0 0 0px;
}
input[type=checkbox]:checked + label
{
background-image:url(facebook_inactive.png);
height: 53px;
width: 77px;
display:inline-block;
padding: 0 0 0 0px;
}


Checkboxes:

<input type='checkbox' name='facebook' id="facebook"><label for="facebook"></label>

<input type='checkbox' name='twitter' id="twitter"><label for="twitter"></label>


My question is how can I style the second checkbox (Twitter) just like I did for the Facebook checkbox. Is there a way to be specific on individual ones so that I can style them independently?

Answer

Click on the images in the Snippet below to see toggle

input[type=checkbox] {
  display: none;
}
#facebook + label {
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRvizk1rdyu1GCcYVDH0rQJtFNwo5lKkICU8Q5byYMAhWslC2uWfw");
  height: 53px;
  width: 77px;
  display: inline-block;
  padding: 0 0 0 0px;
  background-size: contain;
  background-repeat: no-repeat;
}
#facebook:checked + label {
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQTnxDwiDgiIn3IxkbO2d5dzR4F27MtO1JeYmNjJDCZ8JZtzDQmTA");
  height: 53px;
  width: 77px;
  background-repeat: no-repeat;
  background-size: contain;
  display: inline-block;
  padding: 0 0 0 0px;
}
#twitter + label {
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR-I0nSWnXixL0KGa38_32giQZyjT7XPhc78AHCb12nG-jvV7u1SA");
  height: 53px;
  width: 77px;
  display: inline-block;
  padding: 0 0 0 0px;
  background-size: contain;
  background-repeat: no-repeat;
}
#twitter:checked + label {
  background-image: url("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRE0GIa1464BUBgLWNNLtqGRsqkWFSGHOgcBxn_qAO5HJuXEVcvMA");
  height: 53px;
  width: 77px;
  background-repeat: no-repeat;
  display: inline-block;
  padding: 0 0 0 0px;
}
<input type='checkbox' name='facebook' id="facebook">
<label for="facebook"></label>

<input type='checkbox' name='twitter' id="twitter">
<label for="twitter"></label>