Many times wondered in which order the styles are applied to document elements. When you are working on a bigger project or old projects which was written by ex-developers (no offense here) wondered how to over write a particular style or write a style so it has the higher precedence over other style.
We have more ways to add styles to a documents inline Style & external Style both containing
All the above mentioned style have a rating/priority which is used while style the document.
ex: As we know Id (#) selector has precedence over any other selection since ID is unique in a document and obviously they have the highest rating. Any style (inline or external) given using the ID is considered before class, pseudo elements.
ie, with inline style like below
We have more ways to add styles to a documents inline Style & external Style both containing
- Id (#) selector,
- class (.) selector,
- attribute selector (input[type=password]),
- pseudo-classes (:link, :hover:, :visited, :focus, :active) ,
- pseudo-elements (:before, :after, :first-line, :first-letter, :first-child)
All the above mentioned style have a rating/priority which is used while style the document.
ex: As we know Id (#) selector has precedence over any other selection since ID is unique in a document and obviously they have the highest rating. Any style (inline or external) given using the ID is considered before class, pseudo elements.
ie, with inline style like below
- <style> #test { text-decoration:"line-through"; }</style>
- <a id="test" style="text-decoration:line-through;">Test</a>
has the higher specificity that any other style given to the above element.
similarly while considering external stylesheet, the first style (1) has the higher specificity that (2).
Example 1- a#test { text-decoration:"line-through"; }
Example 2- a[id=test] { text-decoration:"none"; }
How is the specificity calculated.
- # (id) selector takes 100 points
- . (class, attribute, pseudo) selectors take 10 points
- type selector, pseudo-element selector take 1 points.
Considering the above example (1 & 2) we can easily say that example 1 style is always selected over example 2. Having said that, there is always some thing beyond the above 3. That is the inline style. Irrespective of any thing, the style attribute takes higher precedence/specificity over any thing (ie it has value 1000 points).
Reference: W3.org (specificity), Css-Tricks
No comments:
Post a Comment