CSS Specificity

Home / CSS / CSS Specificity

CSS Specificity


CSS-Specificity:

CSS specificity is a concept in Cascading Style Sheets (CSS) that determines which styles should be applied to an HTML element when multiple conflicting styles are defined. It's a way to decide which CSS rule takes precedence when there are competing rules targeting the same element.

Specificity is typically calculated based on the following factors, in order of importance:

Inline Styles: Inline styles, defined directly within the HTML element using the style attribute, have the highest specificity. These styles will override any other styles applied to the same element.

Example:

<body>
 <p style="color: red;">This is a red paragraph.</p>
</body>

ID Selectors: Selectors that use the ID attribute have a higher specificity than class selectors and element selectors. An ID selector is written as #elementID.

Example:


 <style>
    #myDiv {
      background-color: blue;
    }
  </style>

Class Selectors and Attribute Selectors: These selectors target elements by their class names or attributes. They are less specific than ID selectors but more specific than element selectors. Class selectors are denoted with a period (.), and attribute selectors target elements based on their attributes.

Example:


<style>
    .button {
      background-color: green;
    }

    [data-type="warning"] {
      color: yellow;
    }
  </style>

Element Selectors: These are the least specific selectors and target elements based solely on their HTML tag names (e.g., p, div, a). They have the lowest specificity.

Example:


<style>
    p {
      font-size: 16px;
    }
  </style>

Pseudo-classes and Pseudo-elements: These selectors target elements based on their state or position within the document. They have varying specificity, but generally, they are less specific than class and attribute selectors.

Example:

 
<style>
    a:hover {
      text-decoration: underline;
    }
    p::first-line {
      font-weight: bold;
    }
  </style>