0
0
CSSmarkup~5 mins

Specificity rules in CSS

Choose your learning style9 modes available
Introduction
Specificity rules help decide which CSS style wins when multiple styles try to change the same thing on a webpage.
You want to change the color of a button but other styles also set its color.
You have many CSS rules and need to know which one applies to a heading.
You want to override a style from a library without changing the library code.
You notice your style is not showing and want to find out why.
You want to write CSS that works well with other styles on the page.
Syntax
CSS
/* Specificity is not written in code but calculated from selectors like: */
#id { ... }       /* id selector */
.class { ... }   /* class selector */
element { ... }  /* element selector */
Specificity counts how many id, class, and element selectors are in a CSS rule.
Higher specificity means the style wins over lower specificity.
Examples
This targets all elements with low specificity.
CSS
p { color: blue; }
This targets elements with class 'highlight' and has higher specificity than element selectors.
CSS
.highlight { color: red; }
This targets the element with id 'main' and has the highest specificity among these examples.
CSS
#main { color: green; }
Combines element and class selectors, so specificity is higher than just element or class alone.
CSS
p.highlight { color: orange; }
Sample Program
This page shows how different CSS selectors with different specificity change the color of paragraphs.
CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Specificity Example</title>
<style>
  p { color: blue; }
  .highlight { color: red; }
  #main { color: green; }
  p.highlight { color: orange; }
</style>
</head>
<body>
  <p>This paragraph is blue because of the element selector.</p>
  <p class="highlight">This paragraph is orange because p.highlight is more specific than .highlight alone.</p>
  <p id="main">This paragraph is green because the id selector #main has the highest specificity.</p>
</body>
</html>
OutputSuccess
Important Notes
If two selectors have the same specificity, the one that comes last in the CSS wins.
Inline styles (style="...") have higher specificity than any selector.
Avoid using too many id selectors to keep CSS flexible.
Summary
Specificity decides which CSS rule applies when multiple rules target the same element.
Id selectors have the highest specificity, then class selectors, then element selectors.
When specificity is equal, the last rule in the CSS wins.