Home > front end >  Select label before an input that is empty and not focused
Select label before an input that is empty and not focused

Time:04-27

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>

CodePudding user response:

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>

CodePudding user response:

You can make life a little easier (since :has support is currently not so great). First, place the input before the label Then, to preserve your original formatting, declare your parent email div as a flex container and reverse its flex row direction.

CSS

.email {
  display: inline-flex;
  flex-direction: row-reverse;
  column-gap: 0.35rem;
}

input[value=""]:not(:focus)   label {
  color: red;
}

JSX

<div className="email">
  <input type="email" id="email" onChange={handleEmail} />
  <label htmlFor="email"> Email </label>
</div>

CodeSandbox example

  • Related