It doesn't have to be important

Published

Estimated Reading Time: 2 minutes

Thanks to collaborated projects, I’ve come across crappy CSS in my life. I talked about it in a [previous article][1].

I’m not impeccable and I wouldn’t be dissing someone else’ because of their faults. However, one point I failed to mention about what I experienced from a co-designer on the project I mentioned in that article was the use of too many nested selectors.

Nested selectors increase specificity and they should be avoided when they can. In an instance where you have

 .header{...} 

which contains a nav. If you wouldn’t be using navs on any other part of your design, it will be unnecessary to have its selector named

.header nav{...}

when it will work just fine as

nav{...}

I had to take that drift because the article is majorly about specificity. Specifically about the use of !important for specificity in CSS.

Based on an article I recently read by Harry Roberts and the words from a lot of a lot of professionals in front-end communities,  it is best to avoid specificity with !important. Harry demonstrated how we can increase specificity without using !important. These pens are simple illustrations:

See the Pen dhxLv by Joseph Rex (@bl4ckdu5t) on CodePen.

See the Pen loCyb by Joseph Rex (@bl4ckdu5t) on CodePen.

The first pen shows how the “bar” class overrides the “foo” class that sets a red color to the paragraph, and the in the second, “foo” has more power. We can add more specificity by chaining the same class as many times as we want it like:

.foo.foo.foo.foo.foo{...} 

Nice right? See we don’t have to do it this way:

.foo{color: red !important; }
.bar{color: blue; }

###Conclusion

There’s a lot more interesting features of CSS which you may not be aware of. To be a great designer, you should take advantage of these features and design the right way.

###Reference

http://csswizardry.com/2014/07/hacks-for-dealing-with-specificity/

[1]: {% post_url 2014-07-24-collaborated-projects-are-good-and-bad %}

show comments