Sponsors

Related Links

CSS Specificity

If you work with CSS you need to know CSS Specificity. This is one of the most important concepts to grasp with css. In this article I'm just going to briefly talk about CSS Specificity as many others have already covered the subject.

There are four things we can style with CSS: Inline, ID, Class and attributes, elements. Each of the four things are assigned a value by css. The total value of the CSS will determine which style is displayed. There is more to CSS than a simple cascade. Cascading only takes effect when the CSS have the same CSS specificity.

Inline Styles - 1,000

Inline styles receive the most weight in the scaling system. They receive a score of 1,000 and overwrite all other styles.

<div style="color:red;">Red</div>

The above will receive a score of 1,000

ID - 100

ID's have the weight of 100.

 
#red { color:red; } /** Score: 100 **/
 
#content #red { color: blue; } /** Score: 200 **/
 

In the above example the score of 200 will win and the content will be displayed as blue (even if the order is reversed). It is important to note that specificity out weighs the cascade.

Classes and Attributes - 10

Both Classes and Attributes receive a score of 10.

 
#content .red { color:red; } /** Score 110 **/
 
#content .blue .red {color:blue; } /** Score 120 **/
 

If the specificity score is the same, this is when the cascade takes effect.

Elements - 1

An element has a weight of 1.

 
#content .red a:hover {color:red;} /** Score: 121 **/
#content div.red a:hover {color:blue;} /** Score: 122 **/
 

Reference

These authors get into a lot more detail than I do on this subject and I recommend you read more on this subject.

If you found this article helpful, please share!

Comments

comments powered by Disqus