20 July 2015

:invalid pseudo class works on form elements too!

Discovered this by accident and there seems to be very little coverage in the blogosphere so I thought I'd share.

You're adding HTML5 validation on your input boxes now, right? And you're using styling to give the user helpful visual feedback, yeah? But did you know that when an input box inside a form is invalid, the parent form also has the :invalid pseudo class? This means we can now style any elements that are a sibling of the invalid input, amazing!

Here's an example where we make the submit button look disabled when an input field is invalid...

<!DOCTYPE html>
    <style type="text/css">
            padding: 0.6em;
            cursor: pointer;
        form:invalid input[type=submit]{
            cursor: default;
            opacity: 0.5;
            border: 1px solid #666;
            border-color: red;
        <input type="text" name="username" pattern="[A-9a-z0-9 ]*" required>
        <input type="submit">

The result is conventional and familiar visual feedback that suggests the form is being disabled/enabled....


Obviously the button is not actually having it's disabled attribute changed, for that you would need some Javascript. But this is a pretty neat, low-level CSS option and remembering that the :invalid pseudo class operates at the parent form level might come in pretty handy.