user348173 user348173 - 1 month ago 6
CSS Question

How to add CSS if element has more than one child?

I have

td
tags and a several
div
inside
td
:

<td>
<div class='test'></div>
<div class='test'></div>
</td>

<td>
<div class='test'></div>
</td>


I want to add
margin-bottom
to
div
if there are more than one in the
td
. How can I do this with the css?

Answer

You can't directly 'count' total numbers of elements in CSS, so there's no way to only apply the class if there's 2 or more divs (you'd need JavaScript for that).

But a possible workaround is to apply the class to all divs in the td...

td > div {
    margin-bottom: 10px;
}

... and then override/disable it with a different style when there's only one element. That indirectly lets you add the style when there's 2+ more child elements.

td > div:only-child {
    margin-bottom: 0px;
}

Alternatively you can apply to every div after the first one, if that happens to work for your situation.

td > div:not(:first-child) {
    margin-bottom: 10px;
}

Edit: Or as Itay says in the comment, use a sibling selector

td > div + div {
    margin-bottom: 10px;
}