2

My question is similar to this: Select label only if input is empty and not focused?

But it's a bit more tricky because I need to select a pseudo-element of the input field if:

  • input field is not focused
  • something is in value

I have no access to the html. I came up with this but no matter what combination I try it's not selecting how I want it.

<input type="text" id="filter" value="lp">

.container input#filter:not([value=""]):not(input:focus)::before {
  content:'';  
}
getimo
  • 25
  • 3
  • Technically you cannot have a pseudo before or after element on an input element (though some browsers might support it). Can you alter the HTML? If so you could consider adding a label element. It would help us give a useful answer if you could add enough to the code to show what you wanted the pseudo element to do. – A Haworth Apr 30 '23 at 10:25

2 Answers2

0

The <input> element is a replaced element and as per the note on MDN:

The pseudo-elements generated by ::before and ::after are contained by the element's formatting box, and thus don't apply to replaced elements such as <img>, or to <br> elements.

This means that no matter what you do, the ::before pseudo-element will never show, even something as benign as:

input::before {
  content: 'foo';
}

Will have no visual effect.

Wongjn
  • 8,544
  • 2
  • 8
  • 24
0

Use this instead

input#filter:not(:placeholder-shown),
input#filter:not(:focus) {
  background-color: red;
}

Also, don't forget to add a placeholder to all the inputs. You can do this with JS:

let temp = document.querySelectorAll("input:not([placeholder]);
temp.forEach((ele)=>{ele.setAttribute("placeholder","text")})
Stephen P
  • 14,422
  • 2
  • 43
  • 67