Reputation: 57
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
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
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.)
lable {
margin: 1em;
border: 1px solid grey;
}
label:focus-within p {
color: red;
}
<label>
<p>text description</p>
<input type="text">
</label>
Upvotes: 1