DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
first-child 與 last-child 的用法與相容性實測
編輯:CSS詳解     

CSS 的偽類在各瀏覽器間差異不小,尤其 IE9 以下的支援相當有限。本文聚焦在兩個最常用的結構偽類::first-child 與 :last-child。

1. :first-child

選出選擇器集合中的第一個元素:

ul li:first-child{ color:red; }
<ul>
<li>first item</li>
<li>second item</li>
<li>third item</li>
<li>last item</li>
</ul>

支援瀏覽器:IE7+、Chrome、Firefox、Safari、Opera。

2. :last-child

選出集合中的最後一個元素:

ul li:last-child{ color:red; }

支援瀏覽器:IE9+、Chrome、Firefox、Safari、Opera。

可以注意到兩者的支援等級差了兩代——:last-child 要到 IE9 才有,這在當年是個不小的限制。

3. 用 expression 硬做相容(效果有限)

網路上流傳用 IE 專用的 expression 來模擬:

ul li{
/* first-child */
background-color:expression(this.previousSibling==null?'#f00':'');
/* last-child */
background-color:expression(this.nextSibling==null?'#f00':'');
}

實測結果並不理想:

  • first-child 的效果在 IE6 中完全沒有顯示出來。
  • last-child 在 IE6、IE7 中顯示正常,但 IE8 依然無效。

結論是這條路走不通。若專案仍需支援老 IE,比較務實的做法是改用 class 明確標記首尾項,例如幫第一項加上 .first、最後一項加上 .last,由後端或模板層負責輸出。與其依賴不可靠的 hack,不如把控制權放回自己手上。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved