문제

When using p:nth-child(1) in the following code, the first paragraph doesn't get selected:

p:nth-child(1) {
  background:#ff0000;
}
<h1>Unrelated</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

Check this jsBin

But when remove a h1 it works, see this jsBin

Any idea why?

도움이 되었습니까?

해결책

p:nth-child(1) is selecting the p element that is also the first child of the parent element (in this case body). There are no p elements that are also the first child of the parent element in this case; the first child of the parent element here is h1. What you want is p:nth-of-type(1) or, more directly, p:first-of-type.

다른 팁

That's because the h1 is the first child in the body.

Use nth-of-type(1) instead, and it will work.

When you use :nth-child() it acts as another selector. It's saying literally, "Give me all elements that are a p that are the first child amongst all their siblings." And you don't have any p tags like that. Your first p tag is a second child.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top