##### 3 組合選擇器 頁面元素比較複雜,存在多個嵌套。為了更加靈活選擇頁面中的元素,CSS中還提供了組合選擇器。組合選擇器就是將多個基本選擇器通過一定的規則連接起來組成一個複雜選擇器。 ###### 後代子代選擇器 ```html Title item1 item2 item3 item4 ` ...
3 組合選擇器
頁面元素比較複雜,存在多個嵌套。為了更加靈活選擇頁面中的元素,CSS中還提供了組合選擇器。組合選擇器就是將多個基本選擇器通過一定的規則連接起來組成一個複雜選擇器。
後代子代選擇器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*後代選擇器*/
.c1 .c2{
color: red;
}
/*子代選擇器*/
.c3 .c5{
color: red;
}
.c3 > .c5{
color: red;
}
.c3 .c4 .c5{
color: red;
}
</style>
</head>
<body>
<!--後代選擇器-->
<div class="c1">
<div class="c2">item1</div>
</div>
<div class="c2">item2</div>
<!--子代選擇器-->
<div class="c3">
<div class="c4">
<div class="c5">item3</div>
</div>
<div class="c5">item4</div>
</div>
</body>
</html>
與或選擇器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*與選擇器 使用 . 相連*/
p.c1{
color: red;
}
/*或選擇器 使用 ,相連*/
p.c1,#i1{
color: red;
}
</style>
</head>
<body>
<!--與選擇器-->
<div class="c1">item1</div>
<p class="c1">item2</p>
<div>item3</div>
<p id="i1">item4</p>
</body>
</html>
兄弟選擇器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*相鄰兄弟選擇器 使用符號 + 連接*/
#i1 + div.c1{
color: red;
}
#i1 + div.c2{
color: red;
}
/*普遍兄弟選擇器 使用符號 ~ 連接*/
#i1 ~ div.c2{
color: red;
}
#i1 ~ div{
color: red;
}
</style>
</head>
<body>
<p id="i1">item0</p>
<div class="c1">item1</div>
<div class="c2">item2</div>
<div class="c3">item3</div>
<div class="c4">item4</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css組合選擇器</title>
<style>
/*.c2{*/
/* color: red;*/
/*}*/
/*子代選擇器*/
.c1 > .c3{
color: chartreuse;
}
/*後代選擇器*/
.c1 .c2 .c3{
color: gold;
}
</style>
</head>
<body>
<div class="c1">
<div class="c2">
<div class="c3">item1</div>
</div>
</div>
<div class="c1">
<div class="c3">item2</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css組合選擇器2</title>
<style>
p.c1, #i1{
color: red;
background-color: darkseagreen;
font-size: 30px;
}
</style>
</head>
<body>
<div class="c1">item1</div>
<p class="c1">item2</p>
<div>item3</div>
<p id="i1">item4</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css組合選擇器3</title>
<style>
/*毗鄰選擇器*/
/*.c2+.c3{*/
/* color: red;*/
/*}*/
/*普通兄弟選擇器*/
.c2 ~ div{
color: gold;
}
</style>
</head>
<body>
<div class="c1">item1</div>
<div class="c2">item2</div>
<div class="c3">item3</div>
<div class="c4">item4</div>
<div class="c5">item5</div>
<p>item6</p>
</body>
</html>
本文來自博客園,作者:生而自由愛而無畏,轉載請註明原文鏈接:https://www.cnblogs.com/zczhaod/p/17640416.html