Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change label color with html and CSS without js?

Tags:

html

css

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>
like image 381
doglover123 Avatar asked Nov 04 '15 00:11

doglover123


1 Answers

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;
}
like image 168
collinksmith Avatar answered Nov 27 '22 03:11

collinksmith