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

允我心安 提交于 2021-02-16 15:58:18

问题


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?


回答1:


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>



回答2:


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>



回答3:


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>


来源:https://stackoverflow.com/questions/2344273/style-a-label-based-on-its-inputs-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!