May 24 2014
CSS Specificity is a technique by which we calculate/identify selector precedence. CSS Specificity explains how parent child relationship is important in CSS. It is difficult to grasp for many beginners what is css specificity and how css specificity works. Many time we face a situation in which our css rules fails to work and we keep scratch our head why rules are not applying. To overcome from such kind of mind boggling situation we should first understand how CSS Specificity works.
Note: Before we move forward i want you to keep in mind that when we talk about CSS Specificity, think about Parent Child relationship of selectors.
In article CSS – Selectors, Properties and Values i explain how to override css rules or css overriding with example which helps you to understand how selectors take higher precedence.
Lets us take a example to understand how CSS Specificity works. I am assuming that you have good knowledge of HTML elements, how to create structure and how to apply css.
Example 1: HTML Structure
<div id="fruits"> <span class="red">Apple</span> <span class="yellow">Mango</span> <span class="orange">Orange</span> <span class="green">Grapes</span> </div>
In above example we have container div and four span having there classes and fruits names. We want to apply the color on fruits names as they look. Like Apple is red in color, Oranges have orange color and so on. We have four classes in our css .red, .yellow, .orange and .green.