bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/CSS/CSS Foundations
CSS•CSS Foundations

CSS Specificity

Overview

CSS specificity is an algorithm that determines which style declaration is ultimately applied to an element. If two or more CSS rules point to the same element, the declaration with the highest specificity will "win", and that style will be applied to the HTML element.

Look at the following examples:

Example

Formula

Here, we have specified a red color for < p > elements.

Result:

The text will be red:

<html> <head> <style>

p {color: red;}

</style> </head> <body>

Formula

< p > Hello World!</p >

</body> </html> Now, look at next example:

Example

Here, we have added a class selector (named "test"), and specified a green color for this class.

Result:

The text will be green, because the class selector has higher specificity: <html> <head>

<style>.test {color: green;}
p {color: red;}

</style> </head> <body> <p class="test">Hello World!</p> </body> </html> Now, look at next example:

Example

Here, we have added the id selector (named "demo").

Result:

The text will be blue, because the id selector has higher specificity: <html> <head> <style>

#demo {color: blue;}.test {color: green;}
p {color: red;}

</style> </head> <body> <p id="demo" class="test">Hello World!</p> </body> </html> Now, look at next example:

Example

Formula

Here, we have added an inline style for the < p > element.

Result:

The text will be pink, because the inline style has the highest specificity: <html> <head> <style>

#demo {color: blue;}.test {color: green;}
p {color: red;}

</style> </head> <body> <p id="demo" class="test"

style="color: pink;">Hello World!</p>

</body> </html>

Previous

CSS Inheritance

Next

CSS The !important Rule