Grow your CSS skills. Land your dream job.

:optional

Last updated on:

The :optional pseudo class targets inputs (including <select>s) that are not specifically set as required (do not have the required attribute).

This can be useful when you want to give optional fields a specific look, maybe slightly less visible than required ones.

Syntax

input[type=text]:optional {
  border: 1px solid #eee;
}

Demo

In the following demo, optional field ("Name", "Gender" and "Continent") have their opacity lowered to 40% so users can immediately know what are the required fields. In this case, "Email". When hovered, an optional input will see the opacity go back to 100%.

The optional works on all type of form elements: text inputs of all types, radio buttons, checkboxes, and selects.

Check out this Pen!

Note: you cannot know with CSS only that a label is associated with an optional field, unless in the label comes after the input (and you use a sibling combinator), which is rare and usually not a good idea. Perhaps in the future parent selectors can help with this.

Related Properties

Other Resources

Browser Support

Chrome Safari Firefox Opera IE Android iOS
10+ 5+ 4+ 10+ 10+ Any 5+

Note that :optional isn't the exact oposite of :not(:required) because the latter will match all types of elements while :optional is restricted to the form elements.

Comments

  1. I’m not sure where you are getting your info, but good topic. I needs to spend some time learning much more or understanding more. Thanks for magnificent info I was looking for this info for my mission.

  2. It’s an awesome paragraph designed for all the internet users; they will take advantage from it I am sure.

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".