CSS3結構性常用僞類選擇器

1.X:first-child

匹配子集的第一個元素,IE7就可以支持。

li:first-child{
            background: red;
        }
2.X:last-child

與firs-child剛好相反,匹配子集的最後一個元素,IE8不支持

li:last-child{
            background: blue;
        }
3.X:nth-child(n)

匹配子集的第n個元素,n從1開始

li:nth-child(5){
            background: #843534;
        }
4.X:nth-last-child(n)

匹配子集的倒數第n個元素

li:nth-last-child(3){
            background: #ffff00;
        }
5.X:nth_child(odd)

匹配子集的奇數元素,1,3,5,7...個元素

 li:nth-child(odd){
            background: #0066dd;
        }
6.X:nth-child(even)

匹配子集的偶數元素,2,4,6,8...個元素

li:nth-child(even){
            background: #ee66cc;
        }
7.X:only-child

這個僞類一般用的比較少,比如上述代碼匹配的是div下的有且僅有一個的p,也就是說,如果div內有多個p,將不匹配。



示例:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        ul{
            background-color: #aaaaaa;
            height: 100px;
        }
        li{
            list-style:none;
            border-radius: 50px;
            background-color: coral;
            height: 100px;
            width: 100px;
            float: left;
            line-height: 100px;
            font-size: 50px;
            text-align: center;
            margin-left: 5px;
            display: block;
        }
        /*奇數*/
        li:nth-child(odd){
            background:#4cae4c;
        }
        /*偶數*/
        li:nth-child(even){
            background: #ee66cc;
        }
        li:first-child{
            background: red;
        }
        li:last-child{
            background: blue;
        }
        li:nth-child(5){
            background: #843534;
        }
        li:nth-last-child(3){
            background: #ffff00;
        }
    </style>
</head>
<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>10</li>
    </ul>
</body>
</html>





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章