<div class="wrapper"> <p class="test1">1</p> <p class="test2">2</p> <p class="test3">3</p> <p class="test4">4</p> <p class="test5">5</p> </div>
p{ width:40px; margin:8px auto; line-height:40px; border:1px solid gray; text-align:center; font-weight: 700; }
X + Y : 相鄰兄弟選擇器 選擇匹配Y的元素,且該元素爲所匹配X元素後面相鄰的位置。html
.test1+p{ background-color:green; color:#fff }
X > Y:子包含選擇器 選擇匹配Y
的元素,且該元素爲所匹配X
元素的子元素。app
.wrapper>p{ background-color:#f5524b; color:#fff; border:none }
X ~ Y: 選擇全部後面的兄弟節點們學習
.test2~p{ background-color:#0eabdf; color:#fff; border:none }
<div class="demo">spa
<a href="" title="標題">1111111111</a> <a href="" title="標題-1">222222222</a> <a href="" title="標題-2">3333333333</a> <a href="" title="標題-3">444444444</a> <a href="" title="名字-1">5555555555</a> <a href="" title="名字-2">6666666666</a> </div>
a { display: block; width:300px; text-align: center; margin: 10px auto; color: #000; text-decoration: none; }
a[title] { background: green; color: #fff; }
a[title="標題"] { background: #ff9900; color: #fff; }
屬性選擇器,上述代碼不僅匹配帶有title
屬性,更匹配title屬性等於」標題」的連接元素
。[]內不僅可用title屬性,還能夠使用其餘屬性。.net
a[title*="標題"]{ background: #3a8aee; color: #fff; }
選擇器匹配屬性值以標題
指定值開頭的每一個元素。code
<ul class="list"> <li>item1</li> <li>item2</li> <li>item3</li> <li>item4</li> <li>item5</li> <li>item6</li> <li><span>item7</span></li> <li>item8</li> </ul>
ul{ list-style: none; } .list li{ line-height:24px }
.list li:first-child{ background-color:yellow; }
:last-child
選擇器用來匹配父元素中最後一個
子元素。htm
nth-child(n)
選擇器匹配父元素中的第n
個子元素。n
能夠是一個數字,一個關鍵字,或者一個公式。blog
.list li:nth-child(2){ background-color:#09ac24; }
Odd 和 even 是可用於匹配下標是奇數或偶數
的子元素的關鍵詞ip
.list li:nth-child(odd) { background:#e73a3a; } .list li:nth-child(even) { background:#f5a72c; }
:nth-last-of-type(n)
選擇器匹配同類型中的倒數第n個同級兄弟元素
。n能夠是一個數字,一個關鍵字,或者一個公式get
.list li:nth-last-child(6) { background-color:#15d6af; }
.list li:nth-child(-n+6) { background: #F05442; color: #fff; }
.list li:nth-child(n+4){
background: #F05442;
color: #fff;
}
:nth-child(-n+6):nth-child(n+3){
background: #F05442;
color: #fff;
}
:nth-of-type(n)
選擇器匹配同類型中的第n個同級兄弟元素。
.list li:nth-of-type(3) { background: #635f5c; }
:only-child
選擇器匹配屬於父元素中惟一子元素
的元素。
span:only-child{ background: #f26f0f; }
:not(selector)
選擇器匹配每一個元素是否是指定的元素/選擇器。
.list li:not(:last-child){ background: #0fcff2; }
參考文章 還須要學習的十二種CSS選擇器
參考文章 CSS選取第幾個標籤元素:nth-child(n)、first-child、last-child