0

I'm new to css and I have some auto generated snippet as following,

<div id="display">
  <div>
      <div>
        <p>red</p>
      </div>
      <div>
        <p>not red</p>
      </div>
    </div>
</div>

I have attached auto generated element into display div (first div) through javascript snippet. I want to select only first paragraph using CSS.

I tried following CSS also tried nth-child(1) ,

p:first-child {
    color:red;
}

But it's selecting both of the values.

5
  • 1
    #display > div > div:first-child p:first-child Commented Jul 15, 2020 at 21:21
  • yes, that's the issue I'm facing here. Those all those auto generated divs only contains same height, width and positions. Which I have added into sample for simplicity Commented Jul 15, 2020 at 21:21
  • @jbutler483 Thanks you for quick working solution. Could you please point me to understand concept of '>' ? Commented Jul 15, 2020 at 21:23
  • You may accept @Barmar 's solution as it does the same thing Commented Jul 15, 2020 at 21:23
  • 1
    That is the direct child operator. So will target a div immediately contained within the parent #display. A good explanation can be found here Commented Jul 15, 2020 at 21:27

3 Answers 3

2

Both <p> elements are the first child of their respective parent DIVs. You want the <p> that's the child of the first child DIV.

div:first-child > p {
  color: red;
}
<div id="display">
  <div>
    <div>
      <p>red</p>
    </div>
    <div>
      <p>not red</p>
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

you can use first-of-type also to achieve that goal

 div:first-of-type > p {
  color: red;
}
<div id="display">
  <div>
    <div>
      <p>red</p>
    </div>
    <div>
      <p>not red</p>
    </div>
  </div>
</div>

Comments

0

#display > div > div:first-child > p{ color: red }

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.