CSS Specificity

When more than one conflicting rules of CSS indicates the same element, then the browser will follow some rules for determining the particular one. Specificity is the way which helps the browsers to decide which property value is most relevant for the element. It determines which style declaration is applied to an element.

Before going in deep about specificity, let's discuss some points about it:

  • The CSS specificity is important only when various selectors are affecting the same element. In this case, the browser needs a way to identify the style to be applied to the matching element, and CSS specificity is the way of doing it.
  • When two or more selectors have equal specificity value, then the latest one considers.
  • Universal selectors (*) and the inherited values have lower specificity, i.e., 0 specificity.
  • The style property has a greater specificity value compare to the selectors (except the !important in the stylesheet selector).
  • The !important alter the selector specificity. When two selectors have equal specificity, then the selector having !important

Specificity hierarchy

Each selector has a place in the hierarchy. There are mainly four categories that define the selector's specificity level:

Inline styles: It is directly attached to the element which is to be styled. For example: <p style="color: red;">. It has the highest priority.

IDs: It is a unique identifier for the elements of a page that has the second-highest priority. For example: #para.

Classes, attributes, and pseudo-classes: It includes classes, attributes, and pseudo-classes (like :focus, :hover, etc.).

Elements and pseudo-elements: It includes the name of elements (div, h1) and pseudo-elements (like :after and :before). They have the lowest priority.

CSS Specificity

Specificity rules

Specificity is the weight, which is applied to the CSS declaration. It is determined by the number of every selector type in the matching selector. Let's see the calculation of specificity.

The specificity rules are discussed below, along with an example.

The specificity of ID selectors is higher than attribute selectors

Let us try to understand it with an example.

Example

In this example, we are going to use the id selector with the background-color property.

Test it Now

In equal specificity, the latest rule will count

In the external stylesheet, if the same rule is applied twice, then the latest (or last) rule will be applied.

Example

In this example, the specificity of the name of elements is same. In this case, the latest specified element name will be considered.

Test it Now

The specificity of class selector is greater than the element selectors

A class selector (.nav, .high, etc.) is highly specific than element selectors (like div, h1, p, etc.)

Example

Test it Now

Next TopicCSS text-indent




Latest Courses