0

Assume we have the following DOM structure and we'd like the Hello world! text to be red if the input element is focused:

<input>
<label>Hello world!</label>

This could easily be achieved using the following css snippet:

input:focus ~ label{
  color: red;
}

Now if we have this HTML structure:

<div>
  <input>
</div>
<label>Hello world!</label>

Same problem: We'd like the label's text to be colored red if the input element inside the div is focused.

But for the life of me I can't figure out the correct CSS combinators.

I tried

div input:focus ~ label{
  color: red;
}

but this only applies to labels that are siblings of the input and are embedded in the same div like so

<div>
  <input>
  <label>Hello world!</label>
</div>

which is not what I want.

It wouldn't be as much of a problem if there was a way of declaring precedence of CSS combinators:

(div input:focus) ~ label{
  color: red;
}

sadly CSS doesn't seem to work like this :|

My question:

Given this HTML code:

<div>
  <input>
</div>
<label>Hello world!</label>

What would the CSS look like that colors the font of the label red iff the input element is focused (i.e. has the :focus pseudo class applied)?

I know this could probably be hacked together with a couple lines of javascript but I'm curious if this is possible with pure HTML and CSS?

Frederik Hoeft
  • 1,177
  • 1
  • 13
  • 37

0 Answers0