0

Here, the div.add-user contains the form for registration. I wanted to apply styles to div.add-user when the input is either :focus or :valid, but I failed to use input:focus + .add-user. I tried to google the problem, but it seems like there is no solution for that. Is that even possible in CSS or should I use JS instead?

<div class="add-user">
   <form id="add-user" action="/" method="post" autocomplete="off">
       <div>
           <input type="text" name="input-name" id="input-name" required>
           ...
       </div>
   </form>
</div>
havaian
  • 5
  • 3
  • 1
    That is not possible. CSS styles only apply one-way in the document tree, and that is down. – Olaf Jul 01 '21 at 05:02

1 Answers1

2

You can use the css :focus-within psudeo class .. Read MDN for more info

See example =>

HTML

<div class="add-user">
  <form id="add-user" action="/" method="post" autocomplete="off">
    <div>
      <input type="text" name="input-name" id="input-name" required>
      ...
    </div>
  </form>
</div>

CSS

  .add-user {
    background: red;

  }
  form {
    border: 1px solid;
    color: gray;
    padding: 4px;
    transition: all 1s ease;
  }

  form:focus-within {
    background: #ff8;
    color: black;
  }

  input {
    margin: 4px;
  }
Sanmeet
  • 1,191
  • 1
  • 7
  • 15
  • Thank you! I did not think about this before, but now I'm familiar with :focus-within pseudo-class – havaian Jul 01 '21 at 15:53
  • @Malik Usmonov I don't think the question was duplicate it has to do nothing with the question tagged as duplicate – Sanmeet Jul 01 '21 at 16:18