css 選擇器之子元素

/*html*/
<div class="wrap">
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
</div>

/*css*/
.wrap{
    display:table;
    width: 200px;
}
.wrap span{
    display:table-cell;
    text-align:center;
}

nth-child(n)

//選擇父元素下的第二個子元素,且爲span
.wrap span:nth-child(2){
    color:red;
}

可是若是子元素是混亂的,好比:css

<div class="wrap">
    <span>1</span>
    <p>p</p>
    <span>2</span>
    <span>3</span>
    <span>4</span>
</div>

nth-child(2)會選擇第2個子元素,並且子元素必須是span,可是沒找到(第二個子元素爲p)html

.wrap span:nth-child(3){
    color:red;
}

nth-child(3)會選擇第3個子元素,並且子元素必須是spanspa

相關3d

  • nth-last-child(n) 從後往前找子元素

nth-of-type(n)

//選擇父元素下的第二個span
.wrap span:nth-of-type(2){
    color:red;
}

一樣的html,nth-of-type(2) 會找到子元素的第2個span,無論有沒有其餘元素阻礙code

相關htm

  • nth-last-of-type(n) 從後往前找子元素

only-child

<div class="wrap">
    <span>1</span>
</div> 

/*css*/
.wrap span:only-child{
    color:red;
}

只有父元素下有一個子元素時,纔會生效
當有其餘任意標籤時,不生效blog

only-child應用比較少table

相關ast

  • last-child 最後一個子元素

only-of-type

對比於only-child,only-of-type容許父元素下有其餘類的子元素class

// 這時會選中惟一的span元素
<div class="wrap">
    <span>1</span>
    <i>2</i>
</div> 
.wrap span:only-of-type{
    color:red;
}

相關

  • first-of-type 選中第一個指定子元素
  • last-of-type 選中最後一個指定子元素
相關文章
相關標籤/搜索