Search code examples
htmlcsscss-selectorscss-specificity

Font-size on parents not changing the p children


I read about the CSS cascading rules and fully aware with that.

  • Inline styling : 1000 pts
  • ID : 100 pts
  • Class : 10 pts
  • Element : 1 pts

But it turned out something weird happens with my code. When I am having higher specificity points, the style does not apply.

Here I am trying to replicate the problem:

p {
  font-size: 10px
}


div.container {
  font-size: 30px !important;
}
<div class="container" style="font-size:20px;">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga nesciunt voluptatum eligendi tempora odio nemo delectus adipisci fugiat quasi quam hic pariatur ea beatae voluptas quae quas, blanditiis incidunt quia.</p>
</div>

The p tag don't follow the font-size I set inline and even on the css files. Even when it is much lower in terms of position and higher in terms of specificity points


Solution

  • It turned out that this is not a specificity points problem but more to inheritance and cascading I think. Glad I learned something now.

    The problem is, setting the font-size to the parents is actually will only be used when the font-size is not set on the target children itself. When it is not set, it will cascade up to the parents until it founds the property of font-size

    But when it is set anywhere even much earlier in terms of position(low priority) or with lower specificity points, it won't cascade up to look up for the font-size property.

    p {
      font-size: 10px
    }
    
    
    div.container {
      font-size: 30px !important;
    }
    
    .container p {
      font-size: 30px;
     }
    <div class="container" style="font-size:20px;">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga nesciunt voluptatum eligendi tempora odio nemo delectus adipisci fugiat quasi quam hic pariatur ea beatae voluptas quae quas, blanditiis incidunt quia.</p>
    </div>

    This one works because I explicitly set the font-size attributes on the p tag inside the div.container itself overriding the earlier styling I set for the p tags

    Note that, if I remove the styling for p tag earlier, it will take the font-size of the parents