Home > front end >  CSS selectors, getting inconsistent behaviour
CSS selectors, getting inconsistent behaviour

Time:06-25

I am in a context of a markdown editor, and came across some inconsistency regarding CSS selectors. Refer to the 4 cases below.

CASE 1:

.mytable tr th {
    color: brown;
    font-size: 18px;
    text-transform: uppercase;
    border-width: 0px;
}
<table >
  <tr>
    <th>TITLE</th>
    <th>DESCRIPTION</th>
  </tr>
</table>

It works as expected i.e. makes border-width equal to 0 as intended. My question is why do the following CSS Style don't equivalently work.

CASE 2:

tr th {
    color: brown;
    font-size: 18px;
    text-transform: uppercase;
    border-width: 0px;
}
<table >
  <tr>
    <th>TITLE</th>
    <th>DESCRIPTION</th>
  </tr>
</table>

Shouldn't it globally apply to any table? I mean it applies to font, but leaves out border-width effect.

CASE 3:

.mytable tr, th {
    color: brown;
    font-size: 18px;
    text-transform: uppercase;
    border-width: 0px;
}
<table >
  <tr>
    <th>TITLE</th>
    <th>DESCRIPTION</th>
  </tr>
</table>

What about this one? Why doesn't this apply to border, but still affects fonts?

CASE 4:

.mytable th {
    color: brown;
    font-size: 18px;
    text-transform: uppercase;
    border-width: 0px;
}
<table >
  <tr>
    <th>TITLE</th>
    <th>DESCRIPTION</th>
  </tr>
</table>

Neither does this one apply to borders. So, how do these case actually work, why don't they affect border-width?

CodePudding user response:

I edited your question to have runnable snippets, and as you can see, all of them are working. If in your local codebase only .mytable tr th is applying, it means there is a specificity issue. It means there is a CSS selector that has a higher specificity than tr th, and .mytable tr, th, and .mytable th, and lower than .mytable tr th that's setting the border-width.

Specificity is the algorithm used by browsers to determine the CSS declaration that is the most relevant to an element, which in turn, determines the property value to apply to the element. The specificity algorithm calculates the weight of a CSS selector to determine which rule from competing CSS declarations gets applied to an element. More on MDN.

  • Related