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.

Mayur
  • 576
  • 2
  • 5
  • 26
  • 1
    `#display > div > div:first-child p:first-child` – jbutler483 Jul 15 '20 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 – Mayur Jul 15 '20 at 21:21
  • @jbutler483 Thanks you for quick working solution. Could you please point me to understand concept of '>' ? – Mayur Jul 15 '20 at 21:23
  • You may accept @Barmar 's solution as it does the same thing – jbutler483 Jul 15 '20 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](https://stackoverflow.com/a/2094512/3436942) – jbutler483 Jul 15 '20 at 21:27

3 Answers3

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>
Barmar
  • 741,623
  • 53
  • 500
  • 612
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>
0

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