Pirune Tirapibal
Pirune Tirapibal

Reputation: 57

change text-color of label on focus input

This is my HTML code:

<label>
    <p>text description</p>
    <input type="text">
</label>

When focus on <input>, I want to change the text-color inside the <p> tag.

How to write the CSS code?

Upvotes: 1

Views: 6650

Answers (2)

Sebastian Brosch
Sebastian Brosch

Reputation: 43564

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>

Upvotes: 6

Paulie_D
Paulie_D

Reputation: 114991

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>

Upvotes: 1

Related Questions