Selectors hierarchy

pexels-photo-59197
War chess by Gladson Xavier

Rules of specificity

The language works with the following specificity rules, from the highest to the lowest :

  1. !important
  2. style=””
  3. #identifier
  4. .class
    [attribute]
  5. tagname

Here’s an example code :

HTML

<blockquote
 id="my-id"
 class="my-class"
 data-attribute="something"
 style="color: purple;"
> With great power comes great responsibilities. </blockquote>

CSS

[data-attribute] { color: orange; }
#my-id { color: red; }
blockquote { color: blue !important; }
.my-class { color: green; }

Output

With great power comes great responsibilities.

 

How to weigh a selector ?

A table can be used to easily calculate the weight of a CSS selector and compare it to any concurrent selector.

a[href].active = 021

identifier class, attribute tag name
 0  2  1

#link.active = 110

identifier class, attribute tag name
 1  1  0

 

BOB – Beware Of Bazookas :

  • An inline style is always worth 1000
  • An !important flag is always worth 10 000
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s