Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style a <label> based on its <input>'s state

Is it possible, with only CSS, to style an HTML label dependent on its input's state?

In my case, I want to style an <input type="checkbox"> based on whether it's checked.

I tried putting the label inside the input, but Firefox and Chrome (at least) seems to parse them as siblings, even though they're clearly nested in the input source. And I don't know how to write a CSS rule that can indirect through a for= attribute.

Do I need to whip out the Javascript on this one?

like image 457
Ken Avatar asked Feb 26 '10 19:02

Ken


1 Answers

They don't need to be nested, that's what the "for" attribute is for in the <label> element.

In modern browsers (those supporting CSS 2.1), you can use a sibling selector, such as

input + label {
  /* rules */
}

You would have to have your markup in a strict sibling relationship, such as:

<input name="cb" id="cb" type="checkbox"><label for="cb">Checkbox</label>
like image 76
Robusto Avatar answered Sep 21 '22 23:09

Robusto