如果元素有多个孩子,如何添加CSS? [英] How to add CSS if element has more than one child?

查看:89
本文介绍了如果元素有多个孩子,如何添加CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 td 标记,并且在 td div c>:

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

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

我想将 margin-bottom 添加到 div 如果 td 中有多个。我怎样才能用CSS来做到这一点?

解决方案

你不能直接'计数'CSS中的元素总数,所以如果有2个或更多div(你需要使用JavaScript),没有办法只应用这个类。



但是可能的解决方法是将类应用于所有在td的div ...

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

...然后使用不同的样式覆盖/禁用它一个元素。这可以间接地让你在有2+以上的子元素时添加样式。

  td> div:只有孩子{
margin-bottom:0px;
}

或者,您可以在第一个div后应用于每个div,为你的情况工作。

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





编辑:或者正如itay在评论中所说的,使用兄弟选择器 p>

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


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?

解决方案

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

这篇关于如果元素有多个孩子,如何添加CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆