Is there a way in CSS to select label
s bound to input
fields (via the for
attribute) having the required
attribute set? Something like:
label:input[required] { ... }
Currently, I'm adding class="required"
to labels and inputs for styling. I now have the HTML5 attribute required="required"
in the required input fields. It would be nice to remove the redundant class attributes.
The closest answer I found doesn't use the label
element's for
attribute, but would require that the label
be directly adjacent to the input in the HTML.
<input type="tel"> <input type="text">
var element = document. querySelector("label[for=email]"); ...or in JavaScript using jQuery: var element = $("label[for=email]");
Input fields without accompanying labels can lead to accessibility issues for those who rely on screen readers. If a screen reader comes across an input field without a label it will try to find some accompanying text to use as the label.
How about CSS 2 Attribute Selectors It is pretty compatible amongst browsers.
Example:
<style> label[required=required] { color: blue; } </style> <label required="required" for="one">Label:</label><input name="one" id="one" />
Also check this out.
This solution works in most modern browsers:
<style> label > input[required="required"] { background: red; } </style> <label for="myField"><input required="required" id="myField" /></label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With