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;
}

但是如果子元素是混亂的,比如:

<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)

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

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

相關

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

nth-of-type(n)

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

同樣的html,nth-of-type(2) 會找到子元素的第2個span,不管有沒有其他元素阻礙

相關

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

only-child

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

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

只有父元素下有一個子元素時,才會生效
當有其他任意標簽時,不生效

only-child應用比較少

相關

  • last-child 最后一個子元素

only-of-type

對比於only-child,only-of-type允許父元素下有其他類的子元素

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

相關

  • first-of-type 選中第一個指定子元素
  • last-of-type 選中最后一個指定子元素


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM