Can you style an active form input's label with just CSS
No. there is unfortunately no predecessor selector in css
input:focus -+ label { ... }
would be lovely.
having the label after the input would be dooable:
input:focus + label { ... }
you could use some positioning to display before...
UPDATED
Make sure you check the draft as this may change: https://drafts.csswg.org/selectors-4/#relational
The :has() relational pseudo-class will allow the selection of parents for example, the following selector matches only <a>
elements that contain an <img>
child:
a:has(> img)
This can be combined with other selectors such as :focus
, :active
or :not
to offer a lot of potential.
Unfortunately browser support isn’t great at the time of writing: https://caniuse.com/#feat=css-has
Adding this for people finding this page in the future. CSS4 will have a parent selector allowing you to choose what element to apply the style to:
I think the current spec allows you to specify which item is matched with a ! sign - the subject selector.
label! > input {
font-weight: bold;
}
This allows far greater control than just parent, for example in this scary chain below the p tag is the target!
article > h1 + section > p! > b > a {
font-style: italic;
}
For completeness, if your input field is within the label you can use focus-within:
HTML:
<label>
<input name="example" type="text">
</label>
CSS:
label:focus-within {
background: #DEF;
}