DEV Community

Himanshu Gupta
Himanshu Gupta

Posted on

Css specificity rules

CSS Specificity refers to the calculation of the importance of CSS rules to determine which style will be applied to an element. In CSS, when multiple styles are conflicting for the same element, the browser uses a set of rules to determine which styles should be applied. These rules are known as CSS Specificity Rules.

The rules are used in the following order of priority:

Inline styles: Inline styles are written directly in the HTML element and have the highest specificity.

IDs: Styles defined using an ID selector have higher specificity than styles defined using a class selector.

Classes, pseudo-classes, and attributes: Styles defined using a class selector, pseudo-class selector, or attribute selector have higher specificity than styles defined using an element selector.

Elements and pseudo-elements: Styles defined using an element selector or pseudo-element selector have the lowest specificity.

If two conflicting styles have the same specificity, the style that appears later in the CSS file will be applied.

It's important to note that CSS Specificity is a complex topic and can be difficult to understand. However, it's important to have a basic understanding of these rules in order to effectively troubleshoot and debug CSS issues.

Here's an example to help illustrate the concept of CSS Specificity:

Let's say we have the following HTML:

Image description

In this example, the text of the paragraph will be displayed in red because the specificity of the class selector .red is higher than the specificity of the ID selector #container p. The inline styles have the highest specificity, but since there are no inline styles in this example, the class selector is applied.

If we add an inline style to the paragraph, the text would be displayed in blue:

Image description

In this case, the inline style has the highest specificity and will be applied, regardless of the class selector or the ID selector in the CSS.

Image description

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git