What is specificity?

Selectors are a frequently used tool in the CSS world. How does an element’s style work when the same element is manipulated using different selectors?

CSS Specificity was designed to solve this problem.

For example

First look at the HTML code structure:

<main class="main">
   <p class="p">Guess what color I am</p>
</main>
Copy the code

Take a look at the CSS code:

.header .p..main .p {
  color: green;
}

:is(.header..main) .p {
  color: purple;
}

:where(.header..main) .p {
  color: red;
}

.p {
  color: blue;
}
Copy the code

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

The correct answer is:purple

parsing

Why is that? In fact, CSS specifies the priority of a selector, which is described in a high-level word, usually translated as “specificity” or “specificity”.

A specificity can be described as a four-digit numeric string separated by dots, similar to the four-digit version number commonly used in versioning: 0.0.0.0.

In order to facilitate understanding, we can even view it as a 4-digit value. The larger the value is, the higher the value is, and the higher the value will cover the lower attributes.

Such as:

In the inline style (Element. Style), the value of specificity is: 1.0.0.0 (1000)

Specificity of ID selector: 0.1.0.0 (0100)

A class selector or pseudo-class has a value of 0.0.1.0 (0010).

The value of a Tag selector (element) and pseudo-element is 0.0.0.1 (0001).

The specificity of the connector and wildcard selector is 0.0.0.0 (0000).

So:

The first two lines of selectors have two class selectors with a higher priority than the next two lines of code. They only have one class selector in effect; Depending on the order in which the CSS code is cascading, the latter will override the previous one, so the browser will render purple as the color of the text.