سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

As I am of the opinion that Quentin's answer is not quite correct, or at least a bit misleading, here is my explanation:

Your ID selector matches the element with the respective ID.

Regarding the inheritance have a look at the CSS Spec.
Paragraph 6.1.1 Specified values says:

User agents must first assign a specified value to each property based on the following mechanisms (in order of precedence):

  1. If the cascade results in a value, use it.
  2. Otherwise, if the property is inherited and the element is not the root of the document tree, use the computed value of the parent element.
  3. Otherwise use the property's initial value. The initial value of each property is indicated in the property's definition.

So the color value of the parent element (<p>) would be inherited (not all properties are inheritable) to the child element (<strong>), but due to your style rule for the strong element, therefore point 1 meets.

Or in other words: Inheritance only takes effect, when there is no other style rule defined for the appropriate element.

Also be aware of that all user agents have a default stylesheet!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top