h2:first-child 和 h2:first-type 没有像我预期的那样工作

h2:first-child and h2:first-type does not work as I expected

我在处理 h2:first-child 和 h2:first-of-type

时遇到问题
h1,
h2 {
  color: #1098ad;
}
h2:first-of-type {
  color: #444;
}

所有 h2 都用 #444 着色,但是当写入 h2:first-child 或 h2:first-of-type 时会覆盖所有 h2,我不知道为什么。 另外,当我这样离开时:

h1
{
  color: #1098ad;
}
h2:first-of-type {
  color: #444;
}

h2:firs-of-type 和 h2:first-child 颜色都是 h2。 这是我的代码(如果有点长请见谅)

* {
  box-sizing: border-box;
  font-family: sans-serif;
  text-align: justify;
  color: #000;
}

.row {
  display: flex;
  gap: 40px;
}

.options {
  font-size: 18px;
  display: flex;
  gap: 20px;
}

.description {
  display: flex;
  gap: 20px;
  align-items: center;
}

h1,
h2 {
  color: #1098ad;
}

h2:first-of-type {
  color: #444;
}

article {
  flex: 1;
  margin-bottom: 0;
}

aside h2 {
  text-align: center;
}

aside {
  margin-top: 20px;
  background-color: #f4f4f4;
  border-top: 5px solid #83989b;
  border-bottom: 5px solid #83989b;
  align-self: flex-start;
  flex: 0 0 230px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <link href="style2.css" rel="stylesheet" />
  <title>My web page</title>
</head>

<body>
  <div class="container">
    <header class="main-header">
      <h1>gomen</h1>
      <nav class="options">
        <a href="#profile">Profile</a>
        <a href="#hobbies">Hobbies</a>
        <a href="#goals">Goals</a>
        <a href="#contact">Contact</a>
      </nav>
    </header>
    <div class="row">
      <article>
        <h2 class="first-child">A little bit about me</h2>
        <section class="profile">
          <h2 id="profile">Profile</h2>
          <div class="description">
            <img src="me.jpeg" alt="owner" height="80" />
          </div>
        </section>
        <section>
          <h2 id="hobbies">Hobbies</h2>
        </section>
        <section>
          <h2 id="goals">Goals</h2>
        </section>
      </article>
      <aside>
        <section>
          <h2 id="contacto">Contact</h2>
        </section>
      </aside>
    </div>
  </div>
  <footer>
    <p>Copyright &copy; 2021 by gomen.</p>
  </footer>
</body>

</html>

:first-of-type 在您的代码中工作正常。

h2:first-of-type 是每个父元素的第一个 h2 子元素,而不是整个文档中的第一个 h2。

h2 {
  color: blue;
}

h2:first-of-type {
  color: red;
}
<body>
    <h2>This is the first h2 type in body</h2>
    <h2>This is the second h2 type in body</h2>
    <div>
      <h2>This is the first h2 type in div</h2>
      <h2>This is the second h2 type in div</h2>
    </div>
    <h2>This is the third h2 type in body</h2>
  </body>

您需要将其隔离为 article 元素中的 h2 元素。

article > h2:first-of-type {
  color: #444;
}