+ 2

The thing seems not relevant but can actually changes other things

Hi there, I had learnt a CSS pseudo selector(or called pseudo class?) button:not(:last-child) {background-color:red;} which I think this code should turn all of the button into red background except the last. when I apply this to the code below: <body> <p>Some Text</p> <button>Btn</button> <button>Btn</button> <button>Btn</button> <button>Btn</button> <p>Some Text</p> </body> I see all of the button colored, then I wrap buttons inside a <div> tag: <body> <p>Some Text</p> <div> <button>Btn</button> <button>Btn</button> <button>Btn</button> <button>Btn</button> </div> <p>Some Text</p> </body> I see actually what I wanted. Why this action can solve the problem? I mean CSS selector "button:not(:last-child)" should have leave the last button uncolored regardless if I have wrap the <div> tag around the button tags. Is there any other problem like this in CSS?

11th Mar 2018, 3:07 PM
kelvin hong 方
kelvin hong 方 - avatar
4 Respuestas
+ 6
:last-child is a relationship question about ALL of the parent's children, that is: the selecting element's siblings...regardless of type. If you want to find the last button amongst all the children (without making a new parent using the div), you want :last-of-type See here: https://css-tricks.com/almanac/selectors/l/last-child/
13th Mar 2018, 11:41 PM
Kirk Schafer
Kirk Schafer - avatar
+ 5
What I see happening: "last-child" in this case is "from the perspective of the wrapping (parent) element" -- which is <body> -- making the last child of <body> the <p> element. You can verify this by: <!--p>Some Text</p--> ...at which point your last button will no longer be red. When you wrap the buttons in a <div> and exclude the <p> elements, you're making the fourth button the last child of the containing <div>.
13th Mar 2018, 8:22 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
@Kirk Schafer So if I wrap only three button only the third button uncolored and the first, second and fourth button colored? It seems counterintuitive to me. I will thinking button:last-child as 'the last button among all of the button no matter how its wrapped', isn't it?
13th Mar 2018, 11:09 PM
kelvin hong 方
kelvin hong 方 - avatar
+ 1
@Kirk Schafer Its helpful! thanks
14th Mar 2018, 10:53 PM
kelvin hong 方
kelvin hong 方 - avatar