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

前端 未结 6 1751
不思量自难忘°
不思量自难忘° 2020-12-28 14:40

I have td tags and a several div inside td:


   
6条回答
  •  北海茫月
    2020-12-28 15:27

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

提交回复
热议问题