伪元素没有正常工作。我做错了吗?Article:first-child

huangapple go评论61阅读模式
英文:

Pseudo element isn't working properly. Am I doing wrong? Article:first-child

问题

I wanted to make the first paragraph red but all the elements are being red.

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="/ex1.css" />
    <style>
      article:first-child {
        background-color: red;
      }
    </style>
    <title>Document</title>
  </head>
  <body>
    <article>
      <h1>heading</h1>
      <p>
        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Porro ratione
      </p>
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate,</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium
      </p>
    </article>
  </body>
</html>

I am expecting that only the first element should be red, but everything is being red.

英文:

I wanted to make the first paragraph red but all the elements are being red.
enter image description here

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="/ex1.css" />
    <style>
      article:first-child {
        background-color: red;
      }
    </style>
    <title>Document</title>
  </head>
  <body>
    <article>
      <h1>heading</h1>
      <p>
        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Porro ratione
      </p>
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate,</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium
      </p>
    </article>
  </body>
</html>

I am expecting that only first element should be red but everything is being red

答案1

得分: 3

您正在针对 article 进行定位。要定位第一个 <p>,您需要改成以下方式:

article p:first-of-type {
  background-color: red;
}

另外,:first-child 用于选择同级元素组中的第一个元素。对于您的用例,:first-of-type 更合适。

英文:

You're targetting article. To target the first &lt;p&gt;, you have to instead do:

article p:first-of-type {
  background-color: red;
}

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

article p:first-of-type {
  background-color: red;
}

<!-- language: lang-html -->

&lt;article&gt;
  &lt;h1&gt;heading&lt;/h1&gt;
  &lt;p&gt;Lorem ipsum dolor sit, amet consectetur adipisicing elit. Porro ratione&lt;/p&gt;
  &lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate,&lt;/p&gt;
  &lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium&lt;/p&gt;
&lt;/article&gt;

<!-- end snippet -->

Additionally, :first-child selects the first element in a group of sibling elements. For your usecase, :first-of-type would work better.

huangapple
  • 本文由 发表于 2023年2月23日 21:10:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定