Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The problem

We all know that CSS selectors are prioritized. When an element satisfies multiple CSS selectors, the CSS selector with the highest priority will take precedence. Let’s learn today.

CSS selectors

Let’s start by looking at what CSS selectors are, as follows

  • Id selector (#test)
  • Class selector (.test), property selector ([class*="test"]), pseudo-class selector (:hover)
  • Label selector (div), pseudo-element selectors (e.g::before)
  • Universal selector (*), descendant selector (>), sibling selector (+.~) etc.

priority

For the above selectors, the order of precedence is

  1. The id selector
  2. (Class selector = property selector = pseudo-class selector)
  3. Label selector = pseudo-element selector
  4. Universal selector = descendant selector (>) = sibling selector (+.~)

Their corresponding priority weights are 0100,0010, 0001, 0000

Additional information:

In addition to the above selectors, CSS also has inline styles. Important Among them! Important has the highest weight, and the inline style is 1000. Both have higher weights than the selector above.

Priority rules:

  • ! importantThe highest,Inline styleNext, go to the top selector.
  • Compare in order, the first is equal, then the next, until the end.
  • If, after the comparison, the weights are equal, the latter overrides the previous style.

example

The first:

  <div class="test">123</div>
  <style>
    div {
      color: green;
    }
    .test {
      color: red;
    }
  </style>
Copy the code

The class selector has a higher weight than the label selector

The second:

  <div class="box">
    <div class="test">123</div>
  </div>
  <style>
     
    .box div:nth-child(1) {
      color: green;
    }
    .box div.test {
      color: red;
    }
  </style>
Copy the code

The weight is 0021 and the style will be overwritten

The third:

  <div class="box">
    <div class="test" style="color: blue">123</div>
  </div>
  <style>
     
    .box div:nth-child(1) {
      color: green;
    }
    .test {
      color: red ! important;
    }
  </style>
Copy the code

! Important has the highest weight