0

I've wrote this in HTML:

<div> hello</div>
<div class="name"><p>hello</p></div>
<div class="name"><p>hello</p></div>

and this in CSS:

div.name:first-child{
  color: red;
}

I would like to change text color of second 'hello' to red. But it doesn't work. What I am doing wrong?

plesniak
  • 13
  • 1
  • 4
  • `:first-child` does just that, selects the first child element. Since you made this selector *more restrictive* by providing a class, it won't match. Whenever you add a CSS class to a pseudo-class it makes it act like a filter. – j08691 Jun 20 '17 at 14:41
  • `
    ` should have parent div then only first-child will work
    – Senthilkumar Govindasamy Jun 20 '17 at 14:45

1 Answers1

2

it's the second child, not the first, use nth-child:

div.name:nth-child(2){
  color: red;
}
<div> hello</div>
<div class="name"><p>hello</p></div>
<div class="name"><p>hello</p></div>
Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
  • True, but I have a feeling the OP wants to select the first div with the class name and it might not always be the second child. – j08691 Jun 20 '17 at 14:44
  • I think you're right. In which case, there's no easy pure css solution that I know of, but `document.querySelector(".name").style.color = "red"` would work. – Scott Weaver Jun 20 '17 at 15:02
  • sweaver2112 This js script look good for me. Now I exercise only css, but thank you for another point of view. It will be halpful in the future. @j08691 - yes, you have a good feeling :) And what do you think about this solution: HTML: `

    hello

    hello

    hello

    ` CSS: `.red{ color:red; }` It is correct?
    – plesniak Jun 20 '17 at 20:28
  • I think that's perfectly valid example of "semantic CSS", which is a good thing. Far better than using the (sure to change) structure of the HTML. – Scott Weaver Jun 21 '17 at 00:39