0
<nav>
    <label class="my-label" for="my-field">hello</label>
</nav>

<form class="my-form" action="" method="GET">
    <input class="my-input" type="text" name="search-field">
</form>

I need a css selector that selects the label.my-label when the input.my-input is focused.

Something like .my-label if .my-input:focused { color: red; }.

This should change the text color of the label to red if the input is focused.

Is there something that can do this in the current browsers?

swift-lynx
  • 1,674
  • 1
  • 8
  • 26
  • There are no ancestor selectors in CSS. You'll need scripting. – isherwood Aug 07 '19 at 12:57
  • Yes, with JavaScript. Or place your label next to the input (which has an existing CSS solution). Why is yours ` – KarelG Aug 07 '19 at 12:59
  • _“Is there something that can do this in the current browsers?”_ - not with that HTML structure. The input field would have to come first, and whatever you want to format based on it having focus, would need to be a sibling of, or inside a sibling of the input field. – misorude Aug 07 '19 at 12:59
  • @KarelG my label is in the navigation because it acts as a "search button" which on click focuses the search field input. when the input filed is focused, the :focus of the input field selector makes it visible – swift-lynx Aug 07 '19 at 13:04
  • you can Achieve it using jquery, Check this: https://codepen.io/kareemda/pen/wVyNQY – Kareem Dabbeet Aug 07 '19 at 13:08
  • 1
    If you place the `label` immediately after the `input` element, you may use `plus(+)`, (`.my-input:focus+.my-label-1 { color: red }`)otherwise, you have to achieve this through the script. – fiveelements Aug 07 '19 at 13:12
  • 1
    and then if the label should be displayed above the input on the screen, you can achieve that by using `display:flex; flex-direction: column-reverse;` on the form. – Mr Lister Aug 07 '19 at 13:14
  • 1
    I don't think you can without changing your HTML,You should move Label tag to bottom of Input tag then use this css: .my-input:focus + .my-label{ color:red; } – R.tbr Aug 07 '19 at 13:52

0 Answers0