Specificity of Selectors in CSS

Lord Analytics
2 min readJul 31, 2023

--

Specificity is a crucial concept in CSS that determines which style rules take precedence when multiple rules target the same HTML element(s). It is used to calculate the specificity value of a selector, which is then used to determine the order of application of the rules. The higher the specificity value, the more weight the selector carries in applying styles to the elements.

Specificity is typically represented as a four-part value, with each part contributing to the overall specificity score:

  1. Inline styles: An inline style has the highest specificity and is represented as “a=1” (or “0,1,0,0” as a four-part value). Since it is directly applied to an element using the style attribute, it overrides other rules.

2. ID selectors: An ID selector is represented as “b=1” (or “0,0,1,0” as a four-part value). It targets elements with a specific id attribute.

3. Class selectors, attribute selectors, and pseudo-classes: These selectors have a specificity value of “c=1” (or “0,0,0,1” as a four-part value). They target elements with specific classes (e.g., .example), attributes (e.g., [type="text"]), or pseudo-classes (e.g., :hover).

4. Element selectors and pseudo-elements: These selectors have the lowest specificity and are represented as “d=1” (or “0,0,0,0,1” as a five-part value). They target HTML elements directly (e.g., div, p) or specific parts of an element (e.g., ::before, ::after).

When comparing two selectors for specificity, the four-part value is used for comparison. The selector with the highest specificity value takes precedence and determines which styles will be applied to the targeted element(s). If two or more rules have the same specificity, the order of appearance in the CSS document will be the tiebreaker.

It’s important to note that the use of !important in CSS can override the cascading rule and force a style to be applied regardless of specificity. However, the use of !important is generally discouraged because it can lead to maintenance issues and make it harder to manage styles effectively.

Understanding specificity helps developers write efficient and maintainable CSS code by ensuring that styles are applied predictably and consistently to HTML elements. By using selectors appropriately and avoiding excessive use of !important, developers can create clear and manageable stylesheets for their web projects.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Lord Analytics
Lord Analytics

Written by Lord Analytics

0 Followers

Adventures, Movies, Technology and Analytics

No responses yet

Write a response