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
https://developer.mozilla.org/en-US/docs/Web/CSS/:has
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
Another possibility :