'How can I set the textColor on a preceding sibling of a input:focus using Tailwind CSS?

I have a situation where I need to change the text color of a label where the following sibling is an input, when its focussed.

div(class='form-control')
  label(class='label ...')
  input(type='text')

The best I can come up with is the move the label to AFTER the input, use the adjacent sibling selector input:focus + label

input:focus + label {
  @apply text-green-500;
}

...and then reverse the order with flexbox flex-direction ... but it means I need to separate the styling into separate CSS file and putting the order 'backward' is highly annoying ...

Are there any tips, tricks or Tailwind utilities to support this use case?



Solution 1:[1]

You can use the group and group-focus-within utilities and keep your markup as is.

<div class="group">
  <label class="group-focus-within:text-red-600">Some text</label>
  <input class="..." />
</div>

Focus-within is now supported in all major modern browsers.

Here it is on Tailwind play https://play.tailwindcss.com/7BRw4QLbly

Solution 2:[2]

For me this answer worked, by setting the :focus-within property in the css on the class of the outer div. In your case it would be:

 form-control:focus-within label {
   @apply text-green-500;
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JHeth
Solution 2 dulvui