0

why all elements were colored on red?

<div class="parent">
  <span>1</span>
  <p>2</p>
  <h1>3</h1>
</div>

.parent:nth-child(1) {
  color: red;
}

.parent:nth-child(2) {
  color: green;
}

.parent:nth-child(3) {
  color: blue;
}

I thought that the elements would be properly colored. span, p, h1 are the children of the element div?

1 Answer 1

4

.parent:nth-child(1) means "An element that is the first child of its parent and which is a member of the parent class".

It won't match the span, p or h1 because they do not have class="parent".

The inherit the red colour from their parent which does have that class and is the first child in its parent.

You need a child or descendant combinator in there:

.parent > :nth-child(1)
.parent :nth-child(1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.