Skip to content Skip to sidebar Skip to footer

Change Text-color Of Label On Focus Input

This is my HTML code: When focus on , I want to change the text-col

Solution 1:

You can't access the previous sibling element (<p>) from <input>.

But you can use the following solution:

label {
  display:flex;
}
p {
  order:-1;
}
input:focus ~ p {
  color:red;
}
<label>
  <input type="text">
  <p>text description</p>  
</label>

Solution 2:

This is possible using the :focus-within pseudo-class selector.

The :focus-within CSS pseudo-class matches any element that the :focus pseudo-class matches or that has a descendant that the :focus pseudo-class matches. (This includes descendants in shadow trees.)

:focus-within @ MDN

Support Details

lable {
  margin: 1em;
  border: 1px solid grey;
}

label:focus-within p {
  color: red;
}
<label>
    <p>text description</p>
    <input type="text">
</label>

Post a Comment for "Change Text-color Of Label On Focus Input"