1. 程式人生 > >CSS3選擇器,篩選指定的index的元素,相容IE7+

CSS3選擇器,篩選指定的index的元素,相容IE7+

1.定義和用法

:nth-child(n) 選擇器匹配屬於其父元素的第 N 個子元素,不論元素的型別。
n 可以是數字、關鍵詞或公式。

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

選取上面結構裡面的li

ul li:nth-child(1){
    color:#fff;
}/*選取第一個li*/
ul li:nth-child(odd){
    color:#fff;
}/*選取偶數*/
ul li:nth-child(even){
    color:#fff;
}/*選取奇數*/
ul li:nth-child(3n+1){
    color:#fff;
}/*選取3n+1個元素*/
由於IE8不支援這種選擇器的寫法,所以一下給出相容性寫法

ul li:first-child{
    color:#fff;
}/*選取第一個li*/
ul li:first-child+li+li{
    color:#fff;
}/*選取第三個li*/
HTMLCode:

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <title>Title</title>
    <style type="text/css">
        ul li {
            border: 1px solid #dfdfdf;
            background: red;
            list-style: none;
            float: left;
        }

        /*CSS3寫法*/
        /*ul li:nth-child(1) {
                width: 25px;
                height: 25px;
            }

            ul li:nth-child(2) {
                width: 50px;
                height: 50px;
            }

            ul li:nth-child(3) {
                width: 100px;
                height: 100px;
            }*/

        div:first-child {
            height: 100px;
        }

            div:first-child + div {
                height: 100px;
            }

        /*相容IE低版本*/
        ul li:first-child {
            width: 25px;
            height: 25px;
        }

            ul li:first-child + li {
                width: 50px;
                height: 50px;
            }

                ul li:first-child + li + li {
                    width: 100px;
                    height: 100px;
                }
    </style>
</head>
<body>

    <div>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>
    <br />
    <div>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>
</body>
</html>
css其他選擇器介紹

    :nth-of-type() 選擇器 ——選擇器匹配屬於父元素的特定型別的第 N 個子元素的每個元素.
    n 可以是數字、關鍵詞或公式。與:nth-child(n)不同的是後者與型別無關。(同樣不支援IE8)

    :first-of-type 選擇器匹配屬於其父元素的特定型別的首個子元素的每個元素。
    提示:等同於 :nth-of-type(1)。(同樣不支援IE8)

    :last-of-type 選擇器匹配屬於其父元素的特定型別的最後一個子元素的每個元素。
    提示:等同於 :nth-last-of-type(1)。(同樣不支援IE8)

    :only-of-type 選擇器匹配屬於其父元素的特定型別的唯一子元素的每個元素。(同樣不支援IE8)

    :nth-last-child(n) 選擇器匹配屬於其元素的第 N 個子元素的每個元素,不論元素的型別,從最後一個子元素開始計數。n 可以是數字、關鍵詞或公式。(同樣不支援IE8)
    提示:請參閱 :nth-last-of-type() 選擇器,該選擇器選取父元素的第 N 個指定型別的子元素,從最後一個子元素開始計數。

    :nth-last-of-type(n) 選擇器匹配屬於父元素的特定型別的第 N 個子元素的每個元素,從最後一個子元素開始計數。n 可以是數字、關鍵詞或公式。(同樣不支援IE8)
    提示:請參閱 :nth-last-child() 選擇器,該選擇器選取父元素的第 N 個子元素,與型別無關,從最後一個子元素開始計數。

    :last-child 選擇器匹配屬於其父元素的最後一個子元素的每個元素。(同樣不支援IE8)
    提示:p:last-child 等同於 p:nth-last-child(1)。

    :first-child 選擇器用於選取屬於其父元素的首個子元素的指定選擇器。對於 IE8 及更早版本的瀏覽器中的 :first-child,需要宣告 。