first-child和last-child的正确理解

580 阅读2分钟

selector:first-child

错误理解: selector选中的第一个元素

正确理解: 如果 selector 所选中的某个节点恰好是其父元素的第一个直接子节点,那么该选择器生效。

示例

示例1

如下示例的 第一个p中的文字并未被设置为红色, 因为p的父元素是html, 而html的第一个直接子节点是h3, 因此p:first-child的css选择器,匹配到的内容是空

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p:first-child{
            color:red;
        }
    </style>
</head>
<body>
    <h3>大标题</h3>
    <p>第一段</p>
    <p>第二段</p>
    <p>第三段</p>
</body>
</html>

image.png

示例2

如下示例的第一个p内的文字会被设置为红色, 因为p的父元素是html, html的第一个直接子元素就是<p>第一段</p>, 所以其文字会被设置为红色

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p:first-child{
            color:red;
        }
    </style>
</head>
<body>
    <p>第一段</p>
    <p>第二段</p>
    <p>第三段</p>
    <h3>大标题</h3>
</body>
</html>

image.png

示例3

不要以为:fist-child只会匹配到一个元素, 仔细看定义 如果 selector 所选中的某个节点恰好是其父元素的第一个直接子节点,那么该选择器生效。, 只要满足定义的元素都会被匹配到, 正如下面的例子所示.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p:first-child{
            color:red;
        }
    </style>
</head>
<body>
    <h3>大标题</h3>
    <p>第一段</p>
    <p>第二段</p>
    <p>第三段</p>
    <div>
        <p>第一句</p>
        <p>第二句</p>
        <p>第三句</p>
    </div>
    <div>
        <h4>标题</h4>
        <p>AAA</p>
        <p>BBB</p>
        <p>CCC</p>
    </div>
    <div>
        <p>大海全是水</p>
        <p>锤子锤子</p>
        <p>不对不对</p>
        <h4>诗歌</h4>
    </div>
</body>
</html>

image.png

selector:last-child

正确理解: 如果 selector 所选中的某个节点恰好是其父元素的最后一个直接子节点,那么该选择器生效。

参考文章

前端常见bug系列1:容易被误解的:last-child 和 :first-child

前端常见bug系列2::last-of-type 和 :first-of-type的误用

前端常见bug系列3:<input type="text">中emoji表情与文字并存时表情被截掉一部分

前端常见bug系列4: JavaScript中忘记类型转换所导致的条件判断错误举例

前端常见兼容问题系列8: 安卓机器中通过JS设置焦点无法拉起软键盘

前端常见兼容性问题系列7: 部分浏览器不支持音频自动播放

前端常见兼容问题系列6: 一些安卓APP的WebView中<input type="file">不工作

前端常见兼容问题系列2:视频哪里去了?