Original article: Conquer Advanced CSS Selectors
Translated from:Taming Advanced CSS Selectors
CSS is one of the most powerful tools available to web designers. Using it we can change the interface of a website in a few minutes without changing the page tags. But despite the fact that each of us realizes that it is useful, CSS selectors are far from reaching their potential, and sometimes we tend to use excessive and useless classes, ids, divs, spans, etc. Our HTML is very messy.
The best way to avoid these plagues in your tags and keep them concise and semantic is to use more complex CSS selectors that can target specific elements without using extra classes or ids, and This way we can also make our code and styles more flexible .
CSS priority
Before delving into the realm of advanced CSS selectors, it's important to understand how CSS priorities work so that we know how to use our selectors appropriately and avoid wasting a lot of time debugging something as long as we pay attention to priorities. It would be easy to solve the problem if
When we write CSS we must be aware that some selectors will be higher than other selectors in the cascade. The selector we write at the end will not necessarily override the styles we wrote earlier on the same element.
So how do you calculate the priority of a given selector ? It's pretty simple if you consider that priorities are expressed as four numbers separated by commas, like: 1, 1, 1, 1 or 0, 2, 0, 1
Let's look at a few examples so it might be easier to understand:
In the example below, the first one will work because it has higher priority than the second one:
It's important to at least have a basic understanding of how priorities work, but some tools like Firebug, when we inspect a specific element, list all CSS selector pairs in order of selector priority to let us know which one is on a specific element. It is useful for selectors to be valid.
It makes it very easy for you to see which selector is acting on an element.
Useful articles: