I am using checkbox type coding and I would like to make it so that for specific options, I am able to click it and it turns blue, and for other options, I can click it and it will turn red or green. I have found a way to do this, as shown in the CSS, but I figured I would have to keep writing code for each type of label. So I was wondering if there was a much more efficient way of doing this? Thanks. Here is the code:
input[type="checkbox"] {
display: none;
}
label {
cursor: pointer;
color: #555;
display: block;
padding: 10px;
margin: 3px;
}
input[type="checkbox"]:checked + label {
color: #ffffff;
font-weight: bold;
background: blue;
}
input[type="checkbox"]:checked + label[for=red1] {
color: #ffffff;
font-weight: bold;
background: red;
}
input[type="checkbox"]:checked + label[for=red2] {
color: #ffffff;
font-weight: bold;
background: red;
}
input[type="checkbox"]:checked + label[for=green1] {
color: #ffffff;
font-weight: bold;
background: green;
}
<div><input id="blue1" type="checkbox" /><label for="blue1">1 blue</label></div>
<div><input id="blue2" type="checkbox" /><label for="blue2">2 blue</label></div>
<div><input id="blue3" type="checkbox" /><label for="blue3">3 blue</label></div>
<div><input id="blue4" type="checkbox" /><label for="blue4">4 blue</label></div>
<div><input id="red1" type="checkbox" /><label for="red1">1 red</label></div>
<div><input id="red2" type="checkbox" /><label for="red2">2 red</label></div>
<div><input id="green1" type="checkbox" /><label for="green1">1 green</label></div>
You can use the CSS 'starts with' attribute selector (^=
) to select all labels with a for
attribute that starts with 'red', 'green', etc.
input[type="checkbox"] {
display: none;
}
label {
cursor: pointer;
color: #555;
display: block;
padding: 10px;
margin: 3px;
}
input[type="checkbox"]:checked + label {
color: #ffffff;
font-weight: bold;
background: blue;
}
input[type="checkbox"]:checked + label[for^=red] {
color: #ffffff;
font-weight: bold;
background: red;
}
input[type="checkbox"]:checked + label[for^=green] {
color: #ffffff;
font-weight: bold;
background: green;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With