30

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?

4

6 回答 6

58

您不能直接“计算” CSS 中的元素总数,因此无法仅在有 2 个或更多 div 的情况下应用该类(为此您需要 JavaScript)。

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

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

...然后在只有一个元素时使用不同的样式覆盖/禁用它。当有 2 个以上的子元素时,这间接地允许您添加样式。

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

或者,您可以在第一个 div 之后应用到每个 div,如果这恰好适合您的情况。

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

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

td > div + div {
    margin-bottom: 10px;
}
于 2013-09-11T09:58:34.790 回答
11

好吧,实际上您可以使用nth-last-child选择器使用 css 执行此操作

小提琴

因此,如果您的标记是这样的:

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

<hr />

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

</table>

CSS

div:nth-last-child(n+2) ~ div:last-child{
    margin-bottom: 40px;
}

...仅当存在具有至少 2 个子 div 的容器时,上述 css 才会设置最后一个 div 元素的样式

只是为了看看这如何更好地工作 - 这是另一个小提琴示例

于 2013-09-11T10:22:23.957 回答
11
td > div:not(:only-child) { margin-bottom: 10px; }
于 2013-12-30T20:52:56.127 回答
5

用接受的答案做了一个很好的小组合

仅当第一个孩子不是唯一的孩子时才将样式应用于第一个孩子。所以当有超过 1 个孩子时

td > div:not(:only-child):first-child { }
于 2016-10-24T17:09:37.610 回答
2

我认为如果不使用 css3,就无法为 td 内的每个 div 添加 10px 边距。

所以一个解决方案是使用javascript并检查td内是否有超过1个div,如果是,则添加一个特殊类。

css

.myMarginClass div{
 margin-bottom:10px;
}

js

var td=document.getElementsByTagName('td'),
l=td.length;
while(l--){
 if(td[l].getElementsByTagName('div').length>1){
  td[l].className='myMarginClass';
 }
}

:only-child 否则对于现代浏览器,@mikel 提出了正确的解决方案

于 2013-09-11T10:06:54.187 回答
2

CSS-Has 对浏览器的支持有限:

但是给你:

td:not(:has(div:first-child:last-child))

奖金:

td:not(:has(div:only-child))
于 2017-04-07T12:10:56.783 回答