Search code examples
cssif-statementstyling

apply css style only by gien child elements



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;
}

Solution

  • 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)