Wednesday, December 26, 2018

html - Doesn't CSS first-child or last-child work with class wise?





Maybe this question is ridiculous, but I want to know this fact. I have a li element with two classes (see below), but it is not working as I expected. Does anybody know the reason?





.red:first-child {
color:#F00;

}
.blue:first-child {
color:#00F; /* not working */
}
.red:last-child {
color:#F00; /* not working */
}
.blue:last-child {
color:#00F;
}



  • one

  • two

  • three

  • one

  • two

  • three






Answer



As others have mentioned, :first-child is working as expected, as the first child of the parent.




The :first-child selector is used to select the specified selector, only if it is the first child of its parent.




Source: CSS :first-child Selector




You can reach the first .blue like this:



.red + .blue


or if you want to get all the .blue after .red



.red ~ .blue



You might want to use :first-of-type which selects the first of a type but then those .blue would have to be a different HTML element.





div.red:first-of-type {
color:#F00;
}
div.red:last-of-type {
color:#00F;
}

p.blue:first-of-type {
color:#F00;
}
p.blue:last-of-type {
color:#00F;
}


one

two

three


one


two


three






No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...