0

According to Specificity Hierarchy ID style should be over tag style, but on the following code snippet, the opposite is happening!

I expect the table to be blue, but it is red, can anyone explain that?

#body table {
    background: red;
}

#table {
    background: blue;
}
<html>
<head>
</head>
<body id="body">
<table id="table">
    <tr>
        <th style="position: sticky;
            top: 0;
            z-index: 1;
            background: gray;">something</th>
    </tr>
    <tr><td>ha</td></tr>
    <tr><td>ha</td></tr>
    <tr><td>ha</td></tr>
    <tr><td>ha</td></tr>
</table>

</body>
</html>
shamaseen
  • 2,193
  • 2
  • 21
  • 35
  • 1
    Because an ID + element selector has a higher specificity than just ID alone. – Terry Sep 22 '21 at 21:42
  • In a sense, both of your styles are ID-based. If you remove `#body` from the first style-- or even just `#`-- you'll get what you expect. – Marc Sep 22 '21 at 21:42
  • @Terry I expected that **the direct ID on the element** will have higher specificity than **Parent ID + the element tag**, doesn't that make sense? – shamaseen Sep 22 '21 at 21:49
  • You add up all the 'elements' of the selector, so `#body` + `table` versus `#table`. So the calculation is done over the entire selector string, not just the last item. – Philip Sep 22 '21 at 21:50

1 Answers1

0

The CSS Specifity CSS Specifity explains it in the section: How to Calculate Specificity?

You had for #body table the following specificity calculation: 100 + 1 = 101 (ID + element)

For the #table you had the following specifity calculation: 100 = 100 (ID)

So #body table has the higher specifity (101 > 100). So as a example you can remove the # from the body body table than the specifity is 1 + 1 = 2 and lower than #table (100).

Marci
  • 302
  • 5
  • 12