在 CSS3 中包含了四种组合方式:
- 后代选取器(以空格分隔)
- 子元素选择器(以大于号分隔)
- 相邻兄弟选择器(以加号分隔)
- 普通兄弟选择器(以波浪号分隔)
后代选取器
后代选取器匹配所有指定元素的后代元素。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PRCORANGE</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)只能选择作为某元素子元素的元素。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PRCORANGE</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>
相邻兄弟选择器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PRCORANGE</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>
普通相邻兄弟选择器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PRCORANGE</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>