Home > Net >  apply css style only by gien child elements
apply css style only by gien child elements

Time:04-18


I was wonderin if you can style for example a li tag of an ul only if another follows. (ul and li are just examples)
Is there a given way? Or do you have to workaround the problem with javascript?

for example:

<ul>
    <li>one</li> <- style this one
    <li>two</li> <- also this one
    <li>tree</li> <- but not this one, because no other li follows
</ul>

I guess you can only do it by overwriting the style of the last element back to the default-style

for example:

li {
    background: #000000f0;
}

li:last-child {
    background: none;
}

CodePudding user response:

your guess is right, use li:last-child and you are good to go. Or you can complicate your life with something like:

li::not(:last-child)

CodePudding user response:

You don’t have to restyle the last element, which has the complication of knowing what the styling was and repeating it.

You can use the not pseudo class

li:not(:last-child) {
  background: #000000f0;
}
  • Related