組合選擇符說明了兩個選擇器直接的關系牢撼。
目錄:
- 后代選取器(以空格分隔)
- 子元素選擇器(以大于號分隔)
- 相鄰兄弟選擇器(以加號分隔)
- 普通兄弟選擇器(以破折號分隔)
后代選取器
后代選取器匹配所有值得元素的后代元素班挖。
以下實例選取所有<p>
元素插入到 <div>
元素中
實例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>后代選取器</title>
<style>
div p
{
background-color:yellow;
}
</style>
</head>
<body>
<div>
<p>段落 1瞪慧。 在 div 中掉缺。</p>
<p>段落 2挪凑。 在 div 中玖喘。</p>
</div>
<p>段落 3澎办。不在 div 中纺酸。</p>
<p>段落 4窖逗。不在 div 中。</p>
</body>
</html>
效果圖
子元素選擇器
與后代選擇器相比吁峻,子元素選擇器(Child selectors)只能選擇作為某元素子元素的元素滑负。
以下實例選擇了<div>
元素中所有直接子元素 <p>
實例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>子元素選擇器</title>
<style>
div>p
{
background-color:yellow;
}
</style>
</head>
<body>
<h1>Welcome to My Homepage</h1>
<div>
<h2>My name is Donald</h2>
<p>I live in Duckburg.</p>
</div>
<div>
<span><p>I will not be styled.</p></span>
</div>
<p>My best friend is Mickey.</p>
</body>
</html>
效果圖
相鄰兄弟選擇器
相鄰兄弟選擇器(Adjacent sibling selector)可選擇緊接在另一元素后的元素,且二者有相同父元素用含。
如果需要選擇緊接在另一個元素后的元素矮慕,而且二者有相同的父元素,可以使用相鄰兄弟選擇器(Adjacent sibling selector)啄骇。
以下實例選取了所有位于<div>
元素后的第一個<p>
元素
實例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>相鄰兄弟選擇器</title>
<style>
div+p
{
background-color:yellow;
}
</style>
</head>
<body>
<h1>Welcome to My Homepage</h1>
<div>
<h2>My name is Donald</h2>
<p>I live in Duckburg.</p>
</div>
<p>My best friend is Mickey.</p>
<p>I will not be styled.</p>
</body>
</html>
效果圖
后續(xù)兄弟選擇器
后續(xù)兄弟選擇器選取所有指定元素之后的相鄰兄弟元素痴鳄。
以下實例選取了所有 <div>
元素之后的所有相鄰兄弟元素 <p>
實例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>后續(xù)兄弟選擇器</title>
<style>
div~p
{
background-color:yellow;
}
</style>
</head>
<body>
<p>之前段落,不會添加背景顏色缸夹。</p>
<div>
<p>段落 1痪寻。 在 div 中。</p>
<p>段落 2虽惭。 在 div 中橡类。</p>
</div>
<p>段落 3。不在 div 中芽唇。</p>
<p>段落 4顾画。不在 div 中取劫。</p>
</body>
</html>
效果圖