سؤال

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