contact@codebetter.in 8823075444
9993928766
  • Tutorials Home
  • Contact

What is the CSS specificity and how does it work?

When more than one set of CSS rules applies to the same element, the browser will have to decide which specific set will be applied to the element.

  1. Inline Styles
  2. ID Selectors
  3. Class Selectors
  4. Element and Pseudo-element Selectors
  1. Inline Styles:
  2. Styles applied directly to an element using the style attribute within the HTML. Inline styles have the highest specificity and override all other rules.
    Example:
    <p style="color: red;">This text is red.</p>
    Output:

    This text is red.

  3. ID Selectors:
  4. Selectors that target elements by their id attribute. They are more specific than classes or element selectors. Example:
    <html>
    <head>
    <style>
    #my-element
    {
    color:green;
    }
    </style>
    </head>
    <body>
    <p id="my-element">This text is green. </p>
    <body>
    <html>
    Output:

    This text is green.

  5. Class Selectors:
  6. Selectors targeting elements by their class or attribute. These selectors have a moderate level of specificity.
    Example:
    <html>
    <head>
    <style>
    .my-class
    {
    color: blue;
    }
    </style>
    </head>
    <body>
    <p class=”my-class>Color is blue</p>
    </body>
    </html>
    Output:

    Color is blue

  7. Element and Pseudo-element Selectors:
  8. Selectors targeting elements by their tag name or pseudo-elements like: before and: after. They have the lowest specificity and are easily overridden by more specific selectors.:
    Example:
    <html>
    <head>
    <style>
    span
    {
    color: pink;
    }
    </style>
    </head>
    <body>
    <span>Color is pink</span>
    </body>
    </html>
    Output:
    Color is pink
Here's how specificity works:
  • Specificity is calculated as a four-part value, such as "a, b, c, d," where "a" represents inline styles, "b" represents IDs, "c" represents classes, attributes, and pseudo-classes, and "d" represents element and pseudo-element selectors.
  • The selector with the highest specificity is chosen, and its styles are applied.
  • If multiple selectors have the same specificity, the one defined later in the stylesheet or in the HTML takes precedence.