skip to Main Content

i add * after a input,
i want select this for change color in input:valid and invalid,
but by this CSS not working why?

form::after {
    content: "*";
}

#fname:invalid~::after {
    background: red;
    border-color: yellow;
}

#fname:valid~::after {
    background: rgb(3, 183, 168);
    border-color: rgb(9, 9, 0);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     <form action="/action_page.php" id="frm">
        <label for="fname">First name:</label><br>
        <input required type="text" id="fname" value=""><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

2

Answers


  1. You can use :has() (supported in Firefox behind the layout.css.has-selector.enabled flag):

    #frm:after {
      content: "*";
    }
    
    #frm:has(#femail:invalid):after {
      background: red;
    }
    
    #frm:has(#femail:valid):after {
      background: rgb(3, 183, 168);
    }
    <form action="?" id="frm">
      <label for="fname">Email:</label><br>
      <input required type="email" id="femail"><br><br>
      <input type="submit" value="Submit">
    </form>

    Or simply replace :after in <form> with, say, <span>*</span>:

    #femail:invalid ~ span {
      background: red;
    }
    
    #femail:valid ~ span {
      background: rgb(3, 183, 168);
    }
    <form action="?" id="frm">
      <label for="fname">Email:</label><br>
      <input required type="email" id="femail"><br><br>
      <input type="submit" value="Submit">
      <span>*</span>
    </form>
    Login or Signup to reply.
  2. Replace ::after with span

    <form action="/action_page.php" id="frm">
        <label for="fname">First name:</label><br>
        <input required type="text" id="fname" value=""><br><br>
        <span>span</span>
        <input type="submit" value="Submit">
    </form>
    
    input:valid + span::after {
      content: "";
      background: red;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search