CSS specificity is the set of rules browsers use to determine which CSS style is applied when multiple rules target the same element. The rule with the higher specificity value takes priority.
- Inline styles have the highest specificity.
- ID selectors override class, attribute, and element selectors.
- Class selectors override element and pseudo-element selectors.
- When specificity is equal, the rule written last is applied.
<html>
<head>
<link rel="stylesheet"
type="text/css"
href="external.css">
<style type="text/css">
h1 {
background-color: red;
color: white;
}
h2 {
color: blue;
}
style>
head>
<body>
<h1>
Internal CSS overrides external CSS
h1>
<h2 style="color: green;">
Inline CSS overrides internal CSS
h2>
body>
html>
/* external.css */
h1 {
background-color: lightgreen;
}
h2 {
color: pink;
}
CSS Specificity Rules
1. Inline CSS
- Inline CSS applied directly to an HTML element using the style attribute.
- Has the highest specificity and overrides both internal and external CSS rules.
2. Internal CSS
- Internal stylesheets defines inside the