Happy holiday folks! All the best from us at Digitpaint

Day 2

Fantastic form pseudo selectors

New pseudo selectors for forms are here! And there's a whole plethora of 'em! Have you ever felt the need to, for instance, put a border around your input element when there is a placeholder visible? Now you can!

All joking aside, these new pseudo selectors are pretty useful. We'll start with a demo. It's the 2nd of december, at the very least, when you read this. Time to order some Christmas ornaments online! Fill out the form and see it react to your input. This is a three part demo, so bear with us.

What kind of ornaments do you want?*

In what colors do you like your ornaments?

Wielding :placeholder-shown

When you fill in your name, the placeholder dissapears. This is how a text-input field behaves naturally. We made it so that the input field displays a label when the placeholder is no longer there. It will go back behind the input field when all text is removed, and the placeholder shows itself again. All of this happens without using JavaScript.

How does this work?

We put a label behind the input field, and used transform: translateY(100%); on a selector with :placeholder-shown. This will then continue to slide the label into view and back behind the textbox as the placeholder appears and dissapears respectively.

Being undecided with :indeterminate

The radio-buttons for the type of ornament are accompanied by an asterisk, which commonly means that this field is required. As an added bonus, we've made the text red as long as none of the options have been chosen. This was done with use of the :indeterminate selector.

In the question about ornament colors, we up the ante and use a little bit of JavaScript to check whether or not all checkboxes in the group are checked. Whenever this is the case, we set the parent checkbox to the indeterminate state and add the "I want them all!" - label, using a ::after pseudo element.

Styling :invalid input

Finally, the demo ends with an email input, which uses the :invalid pseudo selector. This checks whether the user's input is valid according to the element's settings. When the input is thought of as invalid, we add a red border around the input field using the :invalid pseudo selector.

Browser compatibility

So what about browser support for these pseudo selectors? It really depends on the pseudo selector that you want to use. All of the selectors shown above work on every single browser, apart from :placeholder-shown. This one doesn't work on IE or Edge, yet.

  • IE see above
  • Edge see above
  • Chrome
  • FireFox
  • Samsung Internet
  • Chrome for Android
  • Safari
  • iOS Safari
  • opera

More detailed information on caniuse.com for: :placeholder-shown, :invalid & :indeterminate

Further reading

Demo source code

Do you want to dig in the nitty-gritty of this demo, check out the source files:

Back to home