原始网址:http://www.w3schools.com/css/css_combinators.asp
翻译:
CSS Combinators
CSS Combinators
combinator 用以解释选择器之间的关系。 |
CSS 选择器可以包含多个简单选择器,在简单选择器之间,我们可以包含一个 combinator 。
在 CSS3 中,有以下 4 种 combinators:
- 后代选择器(space)
- 子选择器(>)
- 相邻兄弟选择器(+)
- 通用兄弟选择器(~)
Descendant Selector
后代选择器匹配指定元素的所有后代元素。
下列示例为选择 <div>
元素内的所有 <p>
元素:
<!DOCTYPE html>
<html>
<head>
<style>
div p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<span><p>Paragraph 3 in the div.</p></span>
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
Child Selector
子选择器选择指定元素的所有直接子元素。
以下示例为选择 <div>
元素内的所有直接 <p>
元素:
<!DOCTYPE html>
<html>
<head>
<style>
div > p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<span><p>Paragraph 3 in the div.</p></span>
<!-- not Child but Descendant -->
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
Adjacent Sibling Selector
相邻兄弟选择器选择指定元素的所有相邻兄弟元素。
兄弟元素必须有相同的父元素,并且“相邻”的意思是“如影相随”。
以下示例为选择紧随 <div>
元素之后的所有 <p>
元素:
<!DOCTYPE html>
<html>
<head>
<style>
div + p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
</div>
<p>Paragraph 3. Not in a div.</p>
<p>Paragraph 4. Not in a div.</p>
</body>
</html>
General Sibling Selector
通用兄弟选择器选择指定元素的所有兄弟元素。
以下示例为选择 <div>
元素的所有兄弟 <p>
元素:
<!DOCTYPE html>
<html>
<head>
<style>
div ~ p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
</div>
<p>Paragraph 3. Not in a div.</p>
<p>Paragraph 4. Not in a div.</p>
</body>
</html>