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 letting these "plagues" spread in your markup and keep it clean and semantic is to use more complex CSS selectors that can target specific elements without using extra classes or ids. , and in this way we can also make our code and style 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
The first number (a) is usually 0, unless the style attribute is used on the tag;
The second number (b) is the sum of the number of ids on this selector;
The third number (c) is the total of other attribute selectors and pseudo-classes used on this selector. This includes class (.example) and attribute selector (such as li[id=red]);
The fourth number (d) counts elements (like table, p, div, etc.) and pseudo-elements (like: first-line, etc.);
The universal selector (*) has priority 0;
If two selectors have the same precedence, the later one in the style sheet takes effect.
Let's look at a few examples so it might be easier to understand:
#sidebar h2 — 0, 1, 0, 1
h2.title — 0, 0, 1, 1
h2 + p — 0, 0, 0, 2
#sidebar p:first-line — 0, 1, 0, 2
In the example below, the first one will work because it has higher priority than the second one:
#sidebar p#first { color: red; } — 0, 2, 0, 1
#sidebar p:first-line { color: blue; } — 0, 1, 0, 2
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.
Makes it very easy for you to see which selector is acting on an element.