0%

CSS伪类选择器

📃正文

选择第一个子元素

在阅读《CSS权威指南》的过程中,读到关于伪类选择器时的“选择第一个子元素”部分,发现对于伪类 :first-child 存在误解。

<!doctype html>
<html>
  <head>
    <title>test</title>
    <meta charset="utf-8">
    <style>
      p:first-child { font-weight: bold; }
      li:first-child { text-transform: uppercase; }
    </style>
  </head>
  <body>
    <div>
      <p>These are the necessary step:</p>
      <ul>
        <li>Insert key</li>
        <li>Turn key <strong>clockwise</strong></li>
        <li>Push accelerator</li>
      </ul>
      <p> Do <em>not</em> push the brake at the same time as the accelerator.
      </p>
    </div>
  </body>
</html>

之前是将 p:first-child 理解为第一个 p 元素,阅读后发现其真实含义为某元素第一个子元素的所有 p 元素。

演示

伪类的实质为符合:后的要求的元素。

2020年的回顾

看了当时的记录,感觉还是怪怪的。于是改了一下代码再次尝试。

<!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>
    p:first-child {
      font-weight: bold;
      color: red;
    }

    li:first-child {
      text-transform: uppercase;
    }
  </style>
</head>
<body>
  <div>
    <div class="first-child">
      <p>1</p>
      <p>2</p>
      <p>3</p>
    </div>
    <div class="second-child">
      <p>1</p>
      <p>2</p>
      <p>3</p>
    </div>
    <p>These are the necessary step:</p>
    <ul>
      <li>Insert key</li>
      <li>Turn key <strong>clockwise</strong></li>
      <li>Push accelerator</li>
    </ul>
    <p> Do <em>not</em> push the brake at the same time as the accelerator.
    </p>
  </div>
</body>
</html>

image-20201013205859864

查看展示的效果可以看出, p:first-child 的含义解释为,作为第一个子元素的所有 p 标签。