临近同胞选择器

临近同胞选择器将选取紧跟在该元素后的同胞元素。

例如,您可能希望选取<h3>元素,但只想选取<h3>元素后面的<h2>元素。这是一个经常使用的例子,因为它经常应用与现实中。当<h2>和<h3>互相紧邻时,在它们之间往往存在太多空间。代码为:

<body>
<h2>Heading 2 <em>text</em></h2>
<h3>Heading 3 text</h3>
<p>This is <em>text</em> and more <strong>text</strong></p>
</body>

文档树为:

document tree showing adjacent sibling selectors

使用以下规则,您可以选择<h2>后面的<h3>元素:

h2 + h3 {margin: -1em; }

临近同胞选择器同样适用于行内元素例如<em>和<strong>。

document tree showing inline adjacent sibling selectors

使用以下规则,您可以选择<em>元素后面的<strong>元素:

em + strong {color: blue; }

Internet Explorer 5, 5.5 and 6支持临近同胞选择器,但是多数其他的标准兼容浏览器支持。

更多信息

Attribute selectors »

其他的Max Design 文章和演讲
相关链接 webstandardsgroup.org