CSS 派生选择器


派生 取舍器


通过依据元素在其位置的上下文关系来定义 款式,你 可以使标记更加简洁 。

 

在 CSS1 中,通过这种 模式来 利用 规定的 取舍器被称为上下文 取舍器 (contextual selectors),这是由于它们依赖于上下文关系来 利用或者幸免某项 规定 。在 CSS2 中,它们称为派生 取舍器,然而无论你如何 称呼它们,它们的作用都是 雷同的 。

派生 取舍器同意你依据文档的上下文关系来确定某个标签的 款式 。通过 正当地 使用派生 取舍器,我们 可以使 HTML 代码变得更加整洁 。

 

譬如说,你 盼望列表中的 strong 元素变为斜体字,而不是通常的粗体字, 可以这样定义一个派生 取舍器:

 

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


请 留神标记为 <strong> 的蓝色代码的上下文关系:

 

<p><strong>我是粗体字,不是斜体字,由于我不在列表当中,所以这个 规定对我不起作用</strong></p>

<ol>
<li><strong>我是斜体字 。这是由于 strong 元素位于 li 元素内 。</strong></li>
<li>我是 畸形的字体 。</li>
</ol>


在上面的例子中,惟独 li 元素中的 strong 元素的 款式为斜体字,无需为 strong 元素定义特殊的 class 或 id,代码更加简洁 。

 

再看看下面的 CSS 规定:

 

strong {
     color: red;
     }

h2 {
     color: red;
     }

h2 strong {
     color: blue;
     }

 

下面是它施加影响的 HTML:

 

<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>