Highlight shortcut if checked

Is there a way to change the label color other than javascript when the corresponding checkbox is checked?

+86
html css
Mar 11 2018-11-11T00:
source share
4 answers

If you

<div> <input type="checkbox" class="check-with-label" id="idinput" /> <label class="label-for-check" for="idinput">My Label</label> </div> 

You can do

 .check-with-label:checked + .label-for-check { font-weight: bold; } 

See how it works . Please note that this will not work in non-modern browsers.

+114
Mar 11 '11 at 17:07
source share

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

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

I like to rely on the implicit union of the label element and input , so I would 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/

+88
Mar 27 '11 at 23:29
source share

This is an example of using the :checked pseudo-class to make forms more accessible. The :checked class pseudo-class can be used with hidden inputs and their visible shortcuts to create interactive widgets, such as image galleries. I created cut off for people who want to check.

 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> 
+1
Nov 29 '16 at 3:17
source share

You cannot 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 out the working example http://jsfiddle.net/LgADZ/

-eighteen
Mar 11 '11 at 17:08
source share



All Articles