CSS Selector for label bound to input

Viewed 39077

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.

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

you can use label[for="title"] where "title" is the ID of your input. Example:

<label for="title">Title</label>
<input type="text" id="title" name="title">

css:

label[for="title"] {
  color: blue;
}

Well it's not possible in CSS (as I tried) you can easily do it in JS:

let l = document.querySelectorAll('input[required]')
l.forEach(e => {
  e ? e.parentElement.classList.add('required-input') : null;
})

let l = document.querySelectorAll('input[required]')
l.forEach(e => {
  e ? e.parentElement.classList.add('required-input') : null;
})
.required-input label::after {
  content: " *";
  color: red;
}
<div>
  <label for="user">Required</label>
  <input name="user" required/>
</div>
<br>
<div>
  <label for="user">not required</label>
  <input name="user" />
</div>

Related