Software Development | CSS Specificity

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

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:

Activity Instructions

  1. Navigate in your browser to the byui.edu home page.
  2. Open the browser DevTools.
  3. 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.
  4. 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>
  5. In the DevTools Styles pane, look at the rules applied to this anchor element and find the color declarations.
    • How many color declarations 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 :root selector. 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-link is 0-2-0
    .FooterNavigationItem-text-link is 0-1-0
    a is 0-0-1

  6. Review this basic example of specificity in action: Specificity | w3schools.com

Optional Resources