Highlight label if checkbox is checked

HtmlCss

Html Problem Overview


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

Html Solutions


Solution 1 - Html

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>

Solution 2 - Html

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/

Solution 3 - Html

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: #f00;
  font-style: normal;
} 

<input type="checkbox" id="cb_name" name="cb_name"> 
<label for="cb_name">CSS is Awesome</label> 

Solution 4 - Html

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVladimir KeleshevView Question on Stackoverflow
Solution 1 - HtmlAndrew MarshallView Answer on Stackoverflow
Solution 2 - HtmlWalter RumsbyView Answer on Stackoverflow
Solution 3 - HtmlTeocciView Answer on Stackoverflow
Solution 4 - HtmlHusseinView Answer on Stackoverflow