结构伪类选择器

2018-01-22  本文已影响0人  挥剑斩浮云

属性选择器

<input type="text" value="abc"/>
属性选择器   说明
E[attr^="abc"]  选取了元素E,其中E元素定义了属性att,att属性值是以abc开头的任何字符串。
E[attr$="abc"]  选取了元素E,其中E元素定义了属性att,att属性值是以abc结尾的任何字符串。
E[attr*="abc"]  选取了元素E,其中E元素定义了属性att,att属性值任意位置是包含了abc的任何字符串。

结构伪类选择器

div p:first-child{
    /*选择父元素的第一个子元素*/
    background: red;
}
div p:last-child{
    /*选择父元素的最后一个子元素*/
    background: green;
}
div p:nth-child(5){
    /*选择父元素下的第n个元素或奇偶元素,n的值为“数字 | odd | even”*/
    background: yellow;
}
div p:nth-child(odd){
    /*选择父元素下的第n个元素或奇偶元素,n的值为“数字 | odd | even”*/
    background: black;
}
div p:only-child{
    /*选择父元素中唯一的子元素(该父元素只有一个子元素)*/
    background: pink;
}

结构伪类选择器(2)

:first-of-type  选择同元素类型的第1个同级兄弟元素
:last-of-type   选择同元素类型的最后1个同级兄弟元素
:nth-of-type(n) 匹配同元素类型的第n个同级兄弟元素,n的值为“数字 | odd | even”
:only-of-type   匹配父元素中特定类型的唯一子元素(该父元素可以有多个子元素)
<div>
    <h1></h1>
    <p></p>
    <span></span>
    <span></span>
</div>
1):first-child
h1:first-child:选择的是h1元素,因为h1元素是div的第1个子元素。
p:first-child:选择不到任何元素,因为p并不是div的第1个子元素,而是div的第2个子元素。
span:first-child:选择不到任何元素,因为span并不是div的第1个子元素,而是div的第3个子元素;
2):first-of-type
h1:first-of-type:选择的是h1元素,因为h1元素是div中所有h1元素中的第1个h1元素,事实上也只有一个为h1的子元素;
p:first-of-type:选择的是p元素,因为p元素是div中所有p元素中的第1个p元素,事实上也只有一个为p的子元素;
span:irst-of-type:选择的是id="first"的span元素,因为在div元素中有2个span元素,我们选择的是两个之中的第1个

总结:
:first-child是选择父元素下的第1个子元素(不区分元素类型),而:first-of-type是选择父元素下某个元素类型的第1个子元素(区分元素类型)。
:last-child:last-of-typenth-child(n):nth-of-type(n)同样也可以这样去理解

:root选择器

<style type="text/css">
     :root {
        background-color: silver;
    }
    body {
        background-color: red;
    }
</style>
<body>
    <h1>abcde</h1>
</body>
:root{background-color:silver;}
上述代码等价于:
html{background-color:silver;}

:not()选择器

<style type="text/css">
    ul li:not(.first) {
        color: red;
    }
</style>
<ul>
        <li class="first">123</li>
        <li>123</li>
        <li>123</li>
        <li>123</li>
    </ul>

:empty选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <title>CSS3 :empty选择器</title>
    <style type="text/css">
    table,
    tr,
    td {
        border: 1px solid silver;
    }

    td {
        width: 60px;
        height: 60px;
        line-height: 60px;
        text-align: center;
        background-color: #FFA722;
    }

    td:empty {
        background-color: red;
    }
    </style>
</head>
<body>
    <table>
        <tr>
            <td>2</td>
            <td>4</td>
            <td>8</td>
        </tr>
        <tr>
            <td>16</td>
            <td>32</td>
            <td>64</td>
        </tr>
        <tr>
            <td>128</td>
            <td>256</td>
            <td></td>
        </tr>
    </table>
</body>
</html>

:target选择器

上一篇 下一篇

猜你喜欢

热点阅读