views:

63

answers:

2

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?

+2  A: 

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>
Robusto
Ah, I didn't know about sibling selectors (but I should have). This would be perfect, except in this one case it needs to work in IE6, which doesn't seem to support them. Back to JS it is. :-(
Ken
Yeah, IE6 is a cross I have to drag through the world every day, too. Sorry!
Robusto
A: 

Using the adjacent/sibling selector plus the attribute selector would make it work:

<form>
    <style>
    INPUT[checked=checked] + LABEL {
        color: #f00;    
    }
    </style>
    <div>
        <input type="checkbox" id="chk1" />
        <label for="chk1">Label #1</label>
    </div>
    <div>
        <input type="checkbox" id="chk2" checked="checked" />
        <label for="chk2">Label #2</label>
    </div>
</form>
pygorex1