Search code examples
cssinheritancecss-specificity

CSS inheritance vs CSS specificity


I was in a Web Development Class in my University Computer Science Department and the teacher asked the class: "Why a class selector rule was getting applied over a tag selector rule (see example code)?". I answered that it was because of the CSS specificity and I was told I was wrong. The answer he wanted was because of the CSS inheritance.

While it is true, why is the CSS specificity an incorrect answer?

p {
   color: red;
}

.section {
   color: green;
}
<p class="section">Section</p> 

Solution

  • As I said in the comment, I believe you were right: inheritance in CSS is related to the DOM hierarchy. Certain styles are inherited from parent elements.

    Specificity has to do with which CSS rules take precedence over other CSS rules. See below for some examples.

    .container {
      font-size: 35px;
    }
    
    p {
      color: red;
    }
    
    .section {
      color: green;
    }
    
    div.section {
      /* More specific then .section rule */
      color: purple;
    }
    <div class="container">
      <p>
        Example of inheritance. This paragraph has inherited the font-size of its parent.
        <span>This span also inherited font-size.</span>
      </p>
    </div>
    
    <div>
      <p class="section">
        Example of specificity. The "section" class is more specific than the rule created for the p element. Therefore, styles defioned in the "section" class rule may override those defined in the p element rule.
      </p>
      
      <p>
        No class applied.
      </p>
      
      <div class="section">
        The "div.section" rule is more specific than the ".section" rule, so this text is purple.
      </div>
    </div>