Vladimir Keleshev
Vladimir Keleshev

Reputation: 14245

Highlight label if checkbox is checked

Is there a non-javascript way of changing the color of a label when the corresponding checkbox is checked?

Upvotes: 138

Views: 221153

Answers (6)

Felipe N Moura
Felipe N Moura

Reputation: 1617

In case you have the following html structure:

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

You can now use the :has selector:

label:has(input:checked) {
  background-color: orange;
}

I find it a little more elegant and modern, but also, easier to read and spot/understand.

Upvotes: 3

Adnan Khan
Adnan Khan

Reputation: 1

Following is the code to change the label color to green of the checkbox,when it is checked.

input[type=checkbox]:checked +label{
  color: green;
}
<input type="checkbox" id="yes" />
<label for="yes">Yes</label>

input and label are the adjacent sibling tags, selector "+" is used to define the sibling relation between them moreover, ":checked" is a pseudo class in CSS,a CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s),so for us the checked state is considered.

Upvotes: 0

Teocci
Teocci

Reputation: 8865

This is an example of using the :checked pseudo-class to make forms more accessible. The :checked pseudo-class can be used with hidden inputs and their visible labels to build interactive widgets, such as image galleries. I created the snipped for the people that wanna test.

input[type=checkbox] + label {
  color: #ccc;
  font-style: italic;
} 
input[type=checkbox]:checked + label {
  color: #0964aa;
  font-style: normal;
} 
<input type="checkbox" id="cb_name" name="cb_name"> 
<label for="cb_name">CSS is Awesome</label> 

Upvotes: 13

Andrew Marshall
Andrew Marshall

Reputation: 96914

Use the adjacent sibling combinator:

.check-with-label:checked + .label-for-check {
  font-weight: bold;
}
<div>
  <input type="checkbox" class="check-with-label" id="idinput" />
  <label class="label-for-check" for="idinput">My Label</label>
</div>

Upvotes: 184

Walter Rumsby
Walter Rumsby

Reputation: 7535

I like Andrew's suggestion, and in fact the CSS rule only needs to be:

:checked + label {
   font-weight: bold;
}

I like to rely on implicit association of the label and the input element, so I'd do something like this:

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

with CSS:

:checked + span {
    font-weight: bold;
}

Example: http://jsfiddle.net/wrumsby/vyP7c/

Upvotes: 120

Hussein
Hussein

Reputation: 42808

You can't do this with CSS alone. Using jQuery you can do

HTML

<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />

CSS

.highlight{
    background:yellow;
}

jQuery

$('#check').click(function(){
    $('#lab').toggleClass('highlight')
})

This will work in all browsers

Check working example at http://jsfiddle.net/LgADZ/

Upvotes: -31

Related Questions