skip to Main Content

can I display error div only when form has error? I know how to implement by javascript, but, if possible, I want to do this in css only.

I tried write css like following, but it does not work.
input tag anywhere in html. not only case next sibling of error div.

Error div shows only form has :invalid some where in html.

<div id="message">
  error.
</div>

<input class="required" required>

<table>
  <tr>
    <td>
      <input class="required" required>
    </td>
  </tr>
</table>
#message {
  display: none;
}

#message:has(:root .required:invalid) {
  display: block;
}

.required:invalid {
  background: red;
}

You can try this sample by codepen.
https://codepen.io/sforest1975/pen/poxMbYJ

2

Answers


  1. https://developer.mozilla.org/en-US/docs/Web/CSS/:has

    This pseudo-class presents a way of selecting a parent element or a previous sibling element with respect to a reference element by taking a relative selector list as an argument.

    Your #message is not a parent of anything that might be invalid here. And for it to be selected based on any following siblings, you need to use a combinator in your relative selector first.

    #message:has(~ .required:invalid) would select it based on any following invalid input sibling.

    And to target it based on any inputs that are nested into following siblings, you need to allow for (at least) one element "in between" the two, so #message:has(~ * .required:invalid)

    So to make it work for both of those scenarios, you need

    #message:has(~ .required:invalid),
    #message:has(~ * .required:invalid) {
      display: block;
    }
    
    Login or Signup to reply.
  2. Another possibility :

    :root:has(.required:invalid) #message{
      display: block;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search