Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Selector for label bound to input

Is there a way in CSS to select labels 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.

like image 288
Ted Bergeron Avatar asked Jan 16 '10 00:01

Ted Bergeron


People also ask

How do you bind a label to an input element?

<input type="tel"> <input type="text">

How do I select a specific label in CSS?

var element = document. querySelector("label[for=email]"); ...or in JavaScript using jQuery: var element = $("label[for=email]");

Why should a label always be associated with an input?

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.


Video Answer


2 Answers

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.

like image 110
Tom Avatar answered Oct 19 '22 13:10

Tom


This solution works in most modern browsers:

<style>  label > input[required="required"] {     background: red;  }  </style> <label for="myField"><input required="required" id="myField" /></label> 
like image 34
Umberto Babini Avatar answered Oct 19 '22 12:10

Umberto Babini