Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight first invalid form input purely with CSS

I have a form in which all form inputs are required. I want to highlight the first input that's invalid, or rather, not filled in. I thought I could use the first-of-type pseudo selector in conjunction with the invalid pseudo selector, but as soon as I filled in the first input, the selector would not target the next form input that wasn't filled in. Below is my code...

Here's my CSS rule for targeting the first, invalid input.

input:invalid:first-of-type { border: 3px blue solid; }

Here's my form:

<form>
    <legend>Sign Up Info</legend>
    <fieldset>      
        <label>First Name</label><br>
        <input required type="text"><br>
        <label>Last Name</label><br>
        <input required type="text"><br>
        <label>Address</label><br>
        <input required type="text"><br>
    </fieldset>        
</form>

I want to accomplish this purely with CSS because I'm really trying to simplify my Javascript and move anything that can be handled by CSS, rightfully into a stylesheet.

like image 648
Kevin Behan Avatar asked Apr 18 '26 08:04

Kevin Behan


1 Answers

First write a rule highlighting invalid entries:

input:invalid { border: 3px blue solid; }

Then, write a rule saying that inputs following an invalid one will not be highlighted:

input:invalid ~ input { border: 0; }

As you have found, your rule

input:invalid:first-of-type { border: 3px blue solid; }

will not work, because it highlights only the first input, if it is invalid.