What Is CSS Specificity & How Does It Work?
Say you’re building a web page and want all your hyperlinks to be orange to stand out from the other text on the page. Also, for internal links, you not only want to change the font color — you also want to bold them for extra emphasis.
To do this, you add CSS selectors targeting all link elements and the link elements that contain your website name specifically (these are your internal links). But, when you preview the front end of your site, you don’t see the correct formatting for your internal links. What’s the deal?
You likely broke one of the CSS specificity rules and, as a result, will have to backtrack in your code to try to fix the mistake. It’s a pain, but very common. CSS specificity is one of the most difficult — but important — concepts to learn in CSS and frameworks like Bootstrap.
- ID selectors: ID selectors are the most specific kind of selector. They select an element based on its ID attribute (e.g., #my-id).
- Class selectors, attribute selectors, and pseudo-class selectors: These three selector types have equal specificity.
- Class selectors select all elements in a CSS class (e.g., .my-class).
- Attribute selectors select all elements with a given attribute (e.g., p[target]).
- Pseudo-class selectors select elements only when in a special state, like visited or hover (e.g., button:hover).
- Type selectors: These select all HTML elements that have a given node name and have the syntax element (e.g., div).
- Universal selector: The universal selector (*) has no effect on specificity.