Introduction
Specificity rules help decide which CSS style wins when multiple styles try to change the same thing on a webpage.
Jump into concepts and practice - no test required
/* Specificity is not written in code but calculated from selectors like: */ #id { ... } /* id selector */ .class { ... } /* class selector */ element { ... } /* element selector */
p { color: blue; }.highlight { color: red; }
#main { color: green; }
p.highlight { color: orange; }
<!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>
#header is an ID selector, which beats class .menu and element div selectors.#header -> Option A# before the name, classes with ., and combinators like > properly placed.# which is invalid syntax. .container > #main .item is correctly formed..container > #main .item -> Option A.container > #main .item [OK]p { color: blue; }
.content p { color: green; }
#content p { color: red; }p is element selector (lowest), .content p has a class and element, and #content p has an ID and element. ID selector has highest specificity.#content p rule overrides others because ID selectors beat class and element selectors.h1 { color: blue; }
#title { color: red; }
.title { color: green; }<h1 class="title" id="header">Hello</h1>
id="header" and class="title". The selector #title targets an element with ID "title", which does not match.#title does not match, its rule is ignored. The class selector .title applies green, which overrides the element selector blue.#title does not match the element's ID -> Option C.btn { color: black; }
button { color: blue; }
#submit.btn { color: green; }<button id="submit" class="btn">Send</button>
.btn is class selector (specificity 0,1,0), button is element selector (0,0,1), and #submit.btn combines ID and class (1,1,0), highest specificity.#submit.btn selector wins because it has the highest specificity, so the color is green.