CSS Specificity
The CSS specificity is important only when different selectors are affecting the same element. The browser needs a way to identify the style(CSS) to be applied to the matching element, and CSS specificity is the way of doing it.
Specificity hierarchy:
- Inline styles
- IDs
- Classes, attributes, and pseudo-classes
- Elements and pseudo-elements
ID selectors is higher than attribute selectors:
Example:
<!DOCTYPE html> <html> <head> <style> body{ text-align: center; font-size: 30px; color: blue; background-color: #6666ff; } #div1 { background-color: #66ffff; } div#div1 /*Higher specificity*/ { background-color: #66ffff; } div[id=div1] { background-color: #6666ff; } </style> </head> <body> <div id="div1"> Welcome to the I2tutorials </div> </body> </html>
OUTPUT:
the latest rule will count:
Example:
<!DOCTYPE html> <html> <head> <style> body{ font-size: 30px; text-align: center; } div { background-color: yellow; color: red; } div { background-color: red; color: yellow; } </style> </head> <body> <h2> Example of equal specificity </h2> <div> Welcome to the I2tutorials </div> </body> </html>
OUTPUT:
class selector is greater than the element selectors:
Example:
<!DOCTYPE html> <html> <head> <style> .intro { background-color: blue; text-align: center; color: yellow; font-size :40px; } div { background-color: red; text-align: right; color: blue; } </style> </head> <body> <h1>Hello World</h1> <div class="intro">Welcome to the I2tutorials</div> </body> </html>
OUTPUT: