Search code examples
htmlcsscss-specificity

CSS selector priority between id and tag


I know that id is more specific than class and class is more specific than tag.

<!doctype html>
<html>
  <head>
  <meta charset="UTF-8">
  <title>Sample document</title>
  <link rel="stylesheet" href="style1.css">
  </head>
  <body>
    <p id="first">
      <strong class="carrot">C</strong>ascading
      <strong class="spinach">S</strong>tyle
      <strong class="spinach">S</strong>heets
    </p>
    <p id="second">
          <strong>C</strong>ascading
          <strong>S</strong>tyle
          <strong>S</strong>heets
        </p>
  </body>
</html>

style1.css

strong { color: red; }
.carrot { color: orange; }
.spinach { color: green; }
#first { font-style: italic; }
#second { color: cyan; }

The result:

output

It is just like I expected in the first paragraph. But I expected the first letters of the second paragraph would also be cyan since id is more specific than tag.


Solution

  • CSS specificity does not force descendants of selected elements to inherit property values from their parent.

    #second does not match the element <strong>, but strong does.