Change border color of parent div if child input is focused - TailwindCSS
Asked Answered
T

3

7

I know TailwindCSS have class group to use but that is only use for change styles of child element when the parent element activate some event, but I want it in vise versa.

<div class="parent"> <!-- border color should be red when child is focused -->
  <img class="icon">
  <input class="child" type="text">
</div>

And I don't want to re-write css classes. Just use TailwindCSS.

Troth answered 28/11, 2022 at 10:36 Comment(3)
Look for the :focus-within pseudo-class.Bonneau
Does this answer your question? CSS: Change parent on focus of childCordate
@Cordate Yes, but I wonder if is it already has some tailwind class or need to re-write manually. Thank you btw.Troth
G
14

Use focus-within variant

<!-- border will be red when input focuesd -->
<div class="focus-within:border-red-500 border">
  <img class="icon">
  <input class="" type="text">
</div>

DEMO

Gavelkind answered 28/11, 2022 at 11:3 Comment(0)
D
0

You could use JavaScript for that. I assume your input gets focused by clicking. You can catch the click argument and add a class to the parent.

<input class="child" type="text" onclick="focusFunction()">

<script>
function focusFunction() {
    document.getElementByClass("parent").classList.add("focusclass");
}
</script>

Everytime you click the Input, your focusFuncition is called. This function searches for the parent class and adds the focusclass to the class attribute. Of course you can change the naming of the classes.

Maybe you have to give your parent an unique id to select it with getElementByID instead of class if you use the parent class more than once.

Dorothy answered 28/11, 2022 at 10:51 Comment(0)
M
0

You might be looking for the peer class in Tailwind css, to style an element based on the state of a sibling element.

In this case, mark the sibling with the peer class, and use peer-*modifiers to style the target element.

Adding the link to read through the peer classes, if this one addresses your question,

Monoicous answered 6/9 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.