组合器是解释选择器之间关系的东西。
一个 CSS 选择器可以包含多个简单选择器。简单之间 选择器,我们可以包含一个组合器。
CSS 中有四种不同的组合器:
后代选择器(空格)
子选择器 (>)
相邻同级选择器 (+)
通用兄弟选择器 (~)
后代选择器匹配指定元素的后代的所有元素 元素。
以下示例选择 <div> 元素内的所有 <p> 元素:
div p {
background-color: yellow;
}
自己尝试一下 →
<!DOCTYPE html>
<html>
<head>
<style>
div p {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Descendant Selector</h2>
<p>The descendant selector matches all elements that are descendants of a specified element.</p>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section><p>Paragraph 3 in the div.</p></section>
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
子选择器选择属于 a 的子元素的所有元素 指定元素。
以下示例选择所有 <p> 元素 <div> 的子元素 元素:
div > p {
background-color: yellow;
}
自己尝试一下→
<!DOCTYPE html>
<html>
<head>
<style>
div > p {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Child Selector</h2>
<p>The child selector (>) selects all elements that are the children of a specified element.</p>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section>
<!-- not Child but Descendant -->
<p>Paragraph 3 in the div (inside a section element).</p>
</section>
<p>Paragraph 4 in the div.</p>
</div>
<p>Paragraph 5. Not in a div.</p>
<p>Paragraph 6. Not in a div.</p>
</body>
</html>
相邻同级选择器用于选择直接存在的元素 在另一个特定元素之后。
兄弟元素必须具有相同的父元素,“相邻”意味着 “紧接着”。
以下示例选择紧邻 <div> 元素之后放置的第一个 <p> 元素:
div + p {
background-color: yellow;
}
自己尝试一下→
<!DOCTYPE html>
<html>
<head>
<style>
div + p {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Adjacent Sibling Selector</h2>
<p>The + selector is used to select an element that is directly after another specific element.</p>
<p>The following example selects the first p element that are placed immediately after div elements:</p>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
</div>
<p>Paragraph 3. After a div.</p>
<p>Paragraph 4. After a div.</p>
<div>
<p>Paragraph 5 in the div.</p>
<p>Paragraph 6 in the div.</p>
</div>
<p>Paragraph 7. After a div.</p>
<p>Paragraph 8. After a div.</p>
</body>
</html>
通用同级选择器选择指定元素的下一个同级元素的所有元素。
以下示例选择与 <div> 元素相邻的所有 <p> 元素:
div ~ p {
background-color: yellow;
}
自己尝试一下 →
<!DOCTYPE html>
<html>
<head>
<style>
div ~ p {
background-color: yellow;
}
</style>
</head>
<body>
<h2>General Sibling Selector</h2>
<p>The general sibling selector (~) selects all elements that are next siblings of a specified element.</p>
<p>Paragraph 1.</p>
<div>
<p>Paragraph 2.</p>
</div>
<p>Paragraph 3.</p>
<code>Some code.</code>
<p>Paragraph 4.</p>
</body>
</html>
例子 :
div p
示例描述:
选择 <div> 元素内的所有 <p> 元素
例子 :
div > p
示例描述:
选择父元素为 <div> 元素的所有 <p> 元素
例子 :
div + p
示例描述:
选择紧邻 <div> 元素之后放置的第一个 <p> 元素
例子 :
p ~ ul
示例描述:
选择前面有 <p> 元素的每个 <ul> 元素