Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select label before an input that is empty and not focused

I want to select a label (previous sibling) in CSS only when input has no focus and value is '' (empty string)

.email label:not(input[value='']:not(input:focus) ~ label) {
  color: green;
}
<div class='email'>
  <label for='email'>Email</label>
  <input type='email' id='email' value={email} onChange={handleEmail} />
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Selecting a previous sibling in CSS is only possible with the :has() pseudo class which at time of writing is only supported by Safari

Your current selector:

.email label:not(input[value='']:not(input:focus) ~ label)

Has syntactically incorrect parentheses, but if we fix that:

.email label:not(input[value='']):not(input:focus) ~ label

It selects all labels that come after a label that is not an input with value='', that is also not a focused input, which are all descendants of an element with class .email.

Here is how you would implement the selector you want with has():

label:has(+ #email:not(input[value='']:not(input:focus)) {
  color: green;
}
<div className='email'>
  <label htmlFor='email'>Email</label>
  <input type='email' id='email' value={email} onChange={handleEmail} />
</div>

Here is a JavaScript polyfill that you might want to use in the meantime.

Other than that, one possible hack you could use that may or may not be terrible for screenreaders etc. is to reverse the markup and order it back with CSS:

#email:not(input[value='']):not(input:focus)+label {
  color: green;
}

.email {
  width: fit-content;
  display: flex;
  flex-flow: row-reverse wrap;
}
<div class='email'>
  <input type='email' id='email' value={email} onChange={handleEmail} />
  <label htmlFor='email'>Email</label>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading