CSS Specificity
Specificity (or descendant selectors)
It's all related (pun intended) you will hear/read words like parent, child, ancestor, sibling, etc. That is how CSS specificity works.
A "descendant selector" is a way of targeting an element because it's in a specific relationship with other elements. It avoids the need to create/assign over many class names.
Example:
div#nav li a {}
Tip:: read the selector from right to left :: This rule targets an <a> element that has an <li> element somewhere in its ancestry and that <li> element has a <div> with an id of "nav" somewhere in its ancestry.
i.e. You may have already had a div id on your nav section but then felt the need to set up a classname for the links within it, you then would need to add your classname to each link in the HTML, but if you use specificity you don't have to add that extraneous HTML markup. If you do want different styles in your navigation lists just give the <ul> an id then target the majority of them that way. Start at the top of the family tree and work down.
The best way (the ultimate way without scripting perhaps) to allow for sites that may require different styles on different pages, e.g. to show a different background image/color theme for each page, is to use an ID or class on the <body> element.
<body id="homepage"> <h1>My Title</h1>
This allows you to specify general rules for your <h1> element, and then if you want the one on your home page to be styled differently you just target it more specifically.. e.g. to place a different header background on each section of your site..
h1 {color: red; background: #fff;}
#homepage h1 {
background: #fff url(mybgimage.gif) no repeat;
}
That second rule will only target an <h1> element that has any element with the id of "homepage" somewhere in its ancestry. The first rule applies to all <h1>'s so your home page text color will still be red it's only the background you've changed.
There are many more ways that specificity can be used to target elements and the W3C have instructions on calculating specificity which enables you to use it for more advanced targeting purposes.
A selector's specificity is calculated as follows:
- count 1 if the selector is a 'style' attribute rather than a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
- count the number of ID attributes in the selector (= b)
- count the number of other attributes and pseudo-classes in the selector
- count the number of element names and pseudo-elements in the selector (= d)
Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.
Updates:
«« Previous Page | Crib Sheet Index | Next Page»»


ChristinaYoung on