1、CSS選擇器說明
選擇器 | 例子 | 例子描述 | CSS |
---|---|---|---|
:first-child | p:first-child | 選擇屬于父元素的第一個子元素的每個 p元素借卧。 | 2 |
:last-child | p:last-child | 選擇屬于其父元素最后一個子元素每個 p 元素盹憎。 | 3 |
:only-child | p:only-child | 選擇屬于其父元素的唯一子元素的每個 p 元素。 | 3 |
:nth-child(n) | p:nth-child(2) | 選擇屬于其父元素的第二個子元素的每個 p 元素铐刘。 | 3 |
:nth-last-child(n) | p:nth-last-child(2) | 同上陪每,從最后一個子元素開始計數(shù)。 | 3 |
特別注意滨达,選擇的是選中對象在父元素中的第一個元素
2奶稠、基礎(chǔ)效果演示
源代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS偽類選擇器</title>
<style type="text/css">
.div{
width: 100px;
margin: 10px;
}
/*選中元素的第一個元素*/
.div:first-child{
color: red;
}
/*選中元素的最后個元素*/
.div:last-child{
color: blue;
}
/*選中元素的第3個元素*/
.div:nth-child(3){
border: 1px solid red;
}
/*選中元素的倒數(shù)第3個元素*/
.div:nth-last-child(2){
border: 1px solid blue;
}
</style>
</head>
<body>
<div class="div">1</div>
<div class="div">2</div>
<div class="div">3</div>
<div class="div">4</div>
<div class="div">5</div>
</body>
</html>
運行效果:
image.png
3、奇偶選擇器
源代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS偽類選擇器</title>
<style type="text/css">
/*odd 表示選擇基數(shù)行*/
/*even 表示選擇基數(shù)行*/
/*nth-last-child 只是奇偶計算是倒序*/
.div:nth-child(even){
color: red;
}
</style>
</head>
<body>
<div class="div">1</div>
<div class="div">2</div>
<div class="div">3</div>
<div class="div">4</div>
<div class="div">5</div>
</body>
</html>
運行效果捡遍。
image.png
4锌订、有規(guī)律的選擇器
假如我們想實現(xiàn)邊框顯示,元素的計數(shù)是3n+1紅画株、3n+2 綠 辆飘、3n +3 藍色,應(yīng)該如何實現(xiàn)呢谓传?
源代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS偽類選擇器</title>
<style type="text/css">
.div{
width: 100px;
margin: 10px;
}
.div:nth-child(3n+1){
border:1px solid red;
}
.div:nth-child(3n+2){
border:1px solid green;
}
.div:nth-child(3n){
border:1px solid blue;
}
</style>
</head>
<body>
<div class="div">1</div>
<div class="div">2</div>
<div class="div">3</div>
<div class="div">4</div>
<div class="div">5</div>
<div class="div">6</div>
<div class="div">7</div>
<div class="div">8</div>
<div class="div">9</div>
</body>
</html>
運行效果:
image.png
5蜈项、意料之外的顯示
源代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS偽類選擇器</title>
<style type="text/css">
/*odd 表示選擇基數(shù)行*/
/*even 表示選擇基數(shù)行*/
.div:nth-child(even){
color: red;
}
</style>
</head>
<body>
<p class="p">p1</div>
<div class="div">div1</div>
<p class="p">p2</div>
<div class="div">div2</div>
<p class="p">p3</div>
<div class="div">div3</div>
<p class="p">p4</div>
<div class="div">div4</div>
<p class="p">p5</div>
<div class="div">div5</div>
</body>
</html>
運行效果:
??初學的時候我認為如下結(jié)果的錯誤的,預期的結(jié)果應(yīng)該只有div2和div4续挟。事實上這個結(jié)果是對的紧卒,我們仔細閱讀說明會發(fā)現(xiàn),這類選擇器選中的是元素在父元素中的計數(shù)诗祸,因為div元素的位置都是偶數(shù)跑芳,所以出現(xiàn)如下運行結(jié)果。如果我們只想選中div2和div4應(yīng)該如何做呢直颅?first-of-type博个、last-of-type、nth-of-type 和 nth-last-of-type系列選擇器可以幫助我們實現(xiàn)這個愿望功偿。
image.png
CSS選擇器-系列文章
下一節(jié) CSS-選擇器11-first-of-type盆佣、last-of-type、nth-of-type 和 nth-last-of-type