Taming Advanced CSS Selectors

CSS is one of the most powerful tools that is available to web designers (if not the most powerful). With it we can completely transform the look of a website in just a couple of minutes, and without even having to touch the markup. But despite the fact that we are all well aware of its usefulness, CSS selectors are still not used to their full potential and we sometimes have the tendency to litter our HTML with excessive and unnecessary classes and ids, divs and spans.

The best way to avoid these plagues spreading in your markup and keep it clean and semantic, is by using more complex CSS selectors, ones that can target specific elements without the need of a class or an id, and by doing that keep our code and our stylesheets flexible.

CSS Specificity

Before delving into the realms of advanced CSS selectors, it’s important to understand how CSS specificity works, so that we know how to properly use our selectors and to avoid us spending hours debugging for a CSS issue that could be easily fixed if we had only payed attention to the specificity.

When we are writing our CSS we have to keep in mind that some selectors will rank higher than others in the cascade, the latest selector that we wrote will not always override the previous ones that we wrote for the same elements.

So how do you calculate the specificity of a particular selector? It’s fairly straightforward if you take into account that specificity will be represented as four numbers separated by commas, like: 1, 1, 1, 1 or 0, 2, 0, 1

  1. The first digit (a) is always zero, unless there is a style attribute applied to that element within the markup itself
  2. The second digit (b) is the sum of the number of IDs in that selector
  3. The third digit (c) is the sum of other attribute selectors and pseudo-classes in that selector. Classes (.example) and attribute selectors (eg. li[id=red]) are included here.
  4. The fourth digit (d) counts the elements (like table, p, div, etc.) and pseudo-elements (like :first-line)
  5. The universal selector (*) has a specificity of zero
  6. If two selectors have the same specificity, the one that comes last on the stylesheet will be applied

Read More

Taming Advanced CSS Selectors Taming Advanced CSS Selectors Reviewed by BloggerSri on 12:20 AM Rating: 5

No comments:

Powered by Blogger.