CSS Specificity
Overview
CSS stands for Cascading Style Sheets. The cascade is the set of rules a browser uses to decide which declaration wins when several apply to the same element. When competing declarations come from the same source and have the same importance, the browser compares their specificity.
"Specificity is the algorithm used by browsers to determine the CSS declaration that is the most relevant to an element, which in turn, determines the property value to apply to the element. The specificity algorithm calculates the weight of a CSS selector to determine which rule from competing CSS declarations gets applied to an element." – MDN
Prepare
- Read: 📃 Specificity – MDN
- Reference: 📑 Specificity Calculator – enter a selector and see its specificity.
Calculating specificity by hand can be difficult, so get comfortable with the Elements panel in your browser's DevTools. When you select an element, the Styles pane shows every rule that applies to it, crosses out the declarations that lost, and lets you toggle declarations on and off to test.
Specificity is written as three numbers: IDs, then classes/attributes/pseudo-classes, then
elements/pseudo-elements. For example, #nav .item a is 1-1-1. A few special cases to
consider:
- The universal selector
*adds no specificity (0-0-0). - Inline styles (the
styleattribute) override any selector in a stylesheet. - A declaration marked
!importantoverrides normal declarations, regardless of selector specificity. Use it sparingly.
Activity Instructions
- Navigate in your browser to the byui.edu home page.
- Open the browser DevTools.
- In the footer of the page, select the Devotionals link by either 1) right-clicking the link and selecting Inspect, or 2) using the element selector tool in DevTools and then clicking the link.
- You should have an anchor element similar to the following selected in the Elements panel:
<a class="FooterNavigationItem-text-link" href="https://www.byui.edu/speeches/devotionals">Devotionals</a> - In the DevTools Styles pane, look at the rules applied to this anchor element and find the
colordeclarations.- How many
colordeclarations apply to this element? - Which one wins, and which are crossed out?
- Why does the winning declaration apply? Compare the specificity of each selector.
A value such as
var(--primaryTextColor)uses a CSS variable (custom property), usually defined in the:rootselector. Defining values once as variables makes them easy to change throughout the site.You can toggle a declaration by clicking the checkbox to its left in the Styles pane.
Example specificity values
.GlobalFooter .FooterNavigationItem-text-linkis0-2-0
.FooterNavigationItem-text-linkis0-1-0
ais0-0-1 - How many
- Review this basic example of specificity in action: Specificity | w3schools.com
Optional Resources
- 📑 CSS Stats – enter a URL to see statistics about a site's CSS, including a specificity graph.