What are CSS weights

When an element has multiple styles to set, which style will work? This requires a rule to calculate, and that rule is the weight. Whoever has a lot of power, use that pattern.

According to the W3C specification, elements are divided into three levels:

  • Id selector (calledaLevel)
  • Class selectors, property selectors, pseudo classes (we call thembLevel)
  • Tags, pseudo-elements (we call themcLevel)

Calculating weight

So let’s do the classification that we just did, how many a’s do we have, how many B’s do we have, how many C’s do we have.

Example:

body #content .data img:hover
Copy the code

The result of this calculation in the a,b,c format is: 1,2,2.

So let’s analyze it.

There’s 1 A: #content.

There are two B’s: a class:.data and a pseudo-class: :hover.

There are two C’s: body and img

Let’s look at some more examples:

// 0,0,2 (a tag, a pseudo-element) li:first-lineCopy the code
// 0,1,1 (one attribute selector, one label) h1 + *[rel=up]Copy the code
// 1,2(one ID selector, one class selector,2 tags) Body # darkside.sith pCopy the code

Usage method.

Now that we know how to calculate weights, the next step is to see how we can compare who has more weight and who has less weight. Powerful patterns will work.

First of all, compare the first grade A, who has more a’s will have more weight. If you have the same number of A’s, you compare B, just like the rule for A, whoever has more B’s has more weight. If you’re comparing C as well. Same rules.

In this case, whoever has the most power has the power over the elements.

What if the ABC’s are the same in the end? Compare who wrote it last. Usually what comes after overwrites what comes before.

Such as:

 
body div{
    background: blue
}
 
div{
    background: red;
}
Copy the code

For the above two styles, Blue will work.

! importantAnd inline styles

In addition to the above three levels, we have two more, one is inline style, one is! Important.

Inline styles are one step higher than ID selectors. Important is one step higher than inline style.

hierarchy

So the final grade comparison is:

! Important > inline style > ID selector > class selector | attribute selectors | pseudo class selector > tags | pseudo elements

Using the above method, we can calculate the weight and compare the size. You can see which pattern will work.

advice

  • It is not recommended! importantHis grade is too high. It’s hard to break through if you modify the elements later.
  • Can need notid, try not to use it.

The final artifact

Finally, there is a great tool that you can enter a selector and calculate the weights. You can also sort multiple weights.

If it is not clear which weight is larger, using this tool can be clear at a glance, but also convenient for us to learn the weight.

conclusion

If you find anything wrong, please point it out. I hope I can bring you a little harvest.

References:

  • www.w3.org/TR/selector…

  • www.smashingmagazine.com/2007/07/css…