CSS学习----结构伪类选择器(nth-child、nth-o

2020-11-05  本文已影响0人  扮猪老虎吃

结构伪类选择器

作用

根据文档结构来选择器元素。

语法

E:first-child       匹配父元素中的第1个子元素E
E:last-child        匹配父元素中的最后1个子元素E
E:nth-child(n)      n指定具体数值匹配父元素中的第n个子元素E
E:nth-child(n)      n,匹配父元素中的所有子元素E
E:nth-child(2n)     2n,匹配父元素中的所有偶数元素E
E:nth-child(2n+1)   2n+1,匹配父元素中的所有奇数元素E
    可以设置n的表达式
    n+5 从第五个开始一直到后面的所有
    -n+5, 前五个
E:nth-child(even)   匹配父元素中的所有偶数元素E
E:nth-child(odd)    匹配父元素中的所有奇数元素E

注意
nth-child

nth-of-type

示例说明

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* nth-child 会把所有盒子都排列序号 */
        /* 执行的时候会先看 :nth-child(1)之后会去看 前面的div */
        section div:nth-child(1) {
            background-color: red;
            color: yellow;
        }
        /* nth-of-type 会把指定元素的盒子排列序号 */
        /* 执行的时候会先看 div指定的元素  之后会去看 :nth-of-type(1) 第1个孩子 */
        section div:nth-of-type(1) {
            background-color: blue;
            color: yellow;
        }
    </style>
</head>
<body>
    <section>
        <p>光头强</p>
        <div>熊大</div>
        <div>熊二</div>
    </section>
</body>
</html>

效果

上一篇 下一篇

猜你喜欢

热点阅读