国外设计欣赏网站 - DOOOOR.com

 找回密码
 注册

QQ登录

只需一步,快速开始

扫一扫,微信登陆

搜索

[DIV+CSS] CSS 派生选择器

[复制链接]
发表于 11-28-2011 04:15 | 显示全部楼层 |阅读模式

派生选择器

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

在 CSS1 中,通过这种方式来应用规则的选择器被称为上下文选择器 (contextual selectors),这是由于它们依赖于上下文关系来应用或者避免某项规则。在 CSS2 中,它们称为派生选择器,但是无论你如何称呼它们,它们的作用都是相同的。

派生选择器允许你根据文档的上下文关系来确定某个标签的样式。通过合理地使用派生选择器,我们可以使 HTML 代码变得更加整洁。

比方说,你希望列表中的 strong 元素变为斜体字,而不是通常的粗体字,可以这样定义一个派生选择器:

li strong {1 u* B+ {* n1 P, s. e; e* q2 y
    font-style: italic;+ F9 M# N# B+ m% T4 ?
    font-weight: normal;6 N3 f6 y$ x( B  S9 ]( b  L
  }: ^& g* l% ]0 w8 L, l1 C! u

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

<p><strong>我是粗体字,不是斜体字,因为我不在列表当中,所以这个规则对我不起作用</strong></p>
: z% q3 R4 n  Q! d! x
! ^: H4 {/ R: w. y) n+ f9 k<ol>
' O0 f9 g. w8 y<li><strong>我是斜体字。这是因为 strong 元素位于 li 元素内。</strong></li>
' y( P4 d& w# z! }! n<li>我是正常的字体。</li>& j' ]8 X1 h* U
</ol>
  o- _9 J$ W( v2 v% S1 _; m

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

再看看下面的 CSS 规则:

strong {
& i% w, r  t& v. O9 @8 z( U3 W     color: red;! j- ~6 a& y" \& i1 _8 @
     }% Q- ~+ U3 L- e! z

  P0 C* L9 |( J( Sh2 {
1 D# p" c* L! `( E& r( O     color: red;! a9 L$ ?+ Q& ^
     }: u9 ?! _. `- J* G
5 @# J! M  ?3 c+ B& Y8 i2 m# l$ k- t
h2 strong {
1 F) m5 t9 z1 T: S3 {& M     color: blue;1 F4 s5 `4 G4 t+ S* ^
     }

下面是它施加影响的 HTML:

<p>The strongly emphasized word in this paragraph is<strong>red</strong>.</p>6 z9 }4 T( f) k6 M
<h2>This subhead is also red.</h2>
+ W- Z' ?# L( E<h2>The strongly emphasized word in this subhead is<strong>blue</strong>.</h2>

|2011-2026-版权声明|平台(网站)公约|手机版|手机版|DOOOOR 设计网 ( 吉ICP备2022003869号 )

GMT+8, 11-12-2025 02:01 , Processed in 0.191134 second(s), 35 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表