CSS選擇器---nth-child&nth-of-type

nth-child

:nth-child(number)      直接匹配第number個元素複製代碼
:not(:first-child)      除第一個元素以外的子元素複製代碼
:nth-child(n+2)         n+2表示從第二個開始複製代碼
:nth-last-child(n+2)    這樣獲取除最後一個div中全部的div;也能夠用:not(:last-child) 複製代碼
:nth-child(2n)     獲取子元素中第2,4,6,8,... 的元素複製代碼
:nth-child(3n)   獲取子元素中第3,6,9,... 的元素複製代碼
:nth-child(odd)       奇數匹配使用複製代碼
:nth-child(even)        偶數匹配使用複製代碼
上面的選擇器能夠直接在class以後,也能夠在後面加span/p/div等類型後,以下:
/* analysis-res class下的除了第一個以外的元素 */
.analysis-res:not(:first-child) {
    color: #5792b1;
    font-weight: bold;
}

/*  analysis-res class下span標籤中除了第一個以外的元素 */
.analysis-res span:not(:first-child) {
    color: #5792b1;
    font-weight: bold;
}
複製代碼

nth-of-type

nth-of-type要是不研究一下還真容易理bash

解錯,它說的是按照類型來選擇,看下面這個例子。

<style>
  p:nth-of-type(1),p:nth-of-type(3){
    color:red;
  }
</style>
<h1>標題</h1>
<p>這是段落1</p>
<p>這是段落2</p>
<span>這是span1</span>
<span>這是span2</span>
<span>這是span3</span>
<p>這是段落3</p>
複製代碼
效果以下:
複製代碼


這個也不難理解就是按照類型來計算,碰到一個同類型就加1,直到遇到所設定的元素就添加相應樣式:spa

.item:nth-of-type{color:red}複製代碼

那麼直接在class後面:nth-of-type呢?code

<style>
  .item:nth-of-type(3){
    color:red;
  }
</style>
<h1>標題</h1>
<p class="item">這是段落1</p>
<p>這是段落2</p>
<span>這是span1</span>
<span class="item">這是span2</span>
<span class="item">這是span3</span>
<p class="item">這是段落3</p>
<p class="item">這是段落4</p>
<p class="item">這是段落5</p>
複製代碼

效果以下:cdn


總結

  • nth-child
    按照個數來算。blog

  • nth-of-type
    按照類型來計算,同類型不斷加1,直達找到累計的第幾個string

相關文章
相關標籤/搜索