CSS Derived Selector

Derived selectors

By defining styles based on the contextual relationship of an element in its position, you can make the markup more concise.

In CSS1, the selectors used to apply rules in this way are called contextual selectors (contextual selectors) because they depend on the context to apply or avoid certain rules. In CSS2, they are called derived selectors, but regardless of what you call them, their function is the same.

Derived selectors allow you to determine the style of a tag based on the context of the document. By using derived selectors appropriately, we can make the HTML code more organized.

For example, if you want the strong elements in the list to be in italic rather than the usual bold, you can define a derived selector in this way:

li strong {
    font-style: italic;
    font-weight: normal;
  }

Please note the contextual relationship of the blue code marked as <strong>:

<p><strong>I am in bold font, not italic, because I am not in the list, so this rule does not apply to me</strong></p>
<ol>
<li><strong>I am in italic font. This is because the strong element is located within the li element.</strong></li>
<li>I am in normal font.</li>
</ol>

In the above example, only the strong elements within the li elements are styled in italic, so there is no need to define a special class or id for the strong elements, making the code more concise.

Take a look at the following CSS rules:

strong {
     color: red;
     }
h2 {
     color: red;
     }
h2 strong {
     color: blue;
     }

The following is the HTML affected by it:

<p>The strongly emphasized word in this paragraph is<strong>red</strong>.</p>
<h2>This subhead is also red.</h2>
<h2>The strongly emphasized word in this subhead is<strong>blue</strong>.</h2>

Related Content

If you need to learn more about derived selectors, please read the following content in the advanced tutorial on CodeW3C.com: