英文:
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 <p>
, 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 -->
<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>
<!-- end snippet -->
Additionally, :first-child
selects the first element in a group of sibling elements. For your usecase, :first-of-type
would work better.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论