Skip to content Skip to sidebar Skip to footer

Style A

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 based on whether it's checked. I

Solution 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>

Solution 2:

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

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

Solution 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.

<divclass="form-group"><inputtype="checkbox"name="rememberPwd"id="rememberPwd"class="form-input"required/><labelfor="rememberPwd">Remember?</label></div>

Post a Comment for "Style A