What is !important and !optional

Warning – contains large amount of pedantry and punctuation.

For the developers out there, you’ve been trained that things with ! in front of them read as “not this next thing”. != means “not equal to”, !<means “not less than”, and !> means “not greater than”.

Than along comes CSS which basically spits at that. For the non initiated, CSS is a list of rules which webpages follow governing how they’re laid out and how they look. Web elements are selected using classes, ids, or element type. Ids are super specific since you can only have one of them per page, classes are less specific than ids and then element selectors are the least specific. CSS rules get applied by whatever is the most specific.

However, we do have means of making you talk Mr Bond¬†we do have means of breaking the rules of specificity. The !important. Basically, this tells browsers that “even if there’s something more specific than this, listen to this one”. Very handy when you want to override something which came from a framework or library. The notation however, irks me. It looks like its saying “this isn’t very important so don’t listen” based on the usage of ! in every other language I’ve come across.

Things get even more irksome when you start using SASS (which you should, its awesome) and they introduce !optional. This is used within SASS @extend functions (fantastic when you’re using a framework) but @extend can fail on occasion if it can’t find the selector you want to extend.


a.important { font-weight: bold; }
p.message-error { @extend .important; }

This will break since both selectors are specified, making them impossible to unify and you get the error

“No selectors matching “.important” could be unified with “p.message-error”.

Adding !optional to the @extend fixes this since !optional says “if you can’t find it, it doesn’t matter”.

a.important { font-weight: bold; }
p.message-error { @extend .important !optional; }

Apart from the fact that according to convention in EVERY OTHER LANGUAGE it should be saying “this isn’t optional, you do this”.

There’s no real point to this post, it just bothers me.