Jonas
Jonas

Reputation: 62

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

Upvotes: 0

Views: 44

Answers (2)

A Haworth
A Haworth

Reputation: 36664

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

Upvotes: 0

Moebius
Moebius

Reputation: 668

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)

Upvotes: 1

Related Questions