CSS :optional

By  on  

A decade ago HTML and CSS added the ability to, at least signal, validation of form fields. The required attribute helped inform users which fields were required, while pattern allowed developers to provide a regular expression to match against an <input>'s value. Targeting required fields and validation values with just CSS and HTML was very useful.

Did you know that CSS provides :optional to allow you to style form elements that aren't required?

input:optional, select:optional, textarea:optional {
  border: 1px solid #eee;
}

[required] {
  border: 1px solid red;
}

In a sense, it feels like :optional represents :not([required]), but :optional is limited to just form fields.

Recent Features

  • By
    39 Shirts &#8211; Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

Discussion

  1. It’s probably more like :not(:required), right?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!