开发者

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 Chrom开发者_高级运维e (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?


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>


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>


To make this thing work you need to put the label after the input, this goes for text type inputs, so for checkbox you can skip this, unless you want the label before checkbox.

To keep the order for label being shown before the input you need to use Flexbox and reverse order of items, for example like this.

.form-group {
  display: flex;
  flex-direction: column-reverse;
}

The display: flex; with flex-direction: column-reverse; reorders the divs content.

Now all you need to do is use this to affect your label style.

input:checked + label {
  color: #000;
}

And HTML for completeness.

<div class="form-group">
        <input type="checkbox" name="rememberPwd" id="rememberPwd" class="form-input" required/>
        <label for="rememberPwd">Remember?</label>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜