在CSS的表只选择第一行(Select only the first row in a table

2019-07-22 03:21发布

我有一个HTML页面中有许多表格,其中一些仅使用tr & td别人都在用他们能够一切: thead, tbody, tfoot, tr, th & td

因为有些问题,我们正在使用一个CSS规则,使表的顶部和左边框与每个td有自己的右侧和底部边框。

因为这个特别的事情,我们需要得到td的所有四角圆其特定的角落。

我怎样才能做一个单一的规则,可以在表中只选择第一行?

我使用这个规则至今:

table.unit tr:first-child td:first-child, table.units thead tr:first-child th:first-child {
  border-top-left-radius: 10px;
}
table.unit tr:first-child td:last-child, table.units thead tr:first-child th:last-child {
  border-top-right-radius: 10px;
}

在此的jsfiddle你可以看到我的问题:( http://jsfiddle.net/NicosKaralis/DamGK/ )

  • 有没有在同一时间解决了2所实现的方法吗?
  • 如果有,我该怎么办呢?
  • 如果没有,你能帮助我做到这一点的最好方法是什么?

PS:我可以改变表的元素,但它会让这么多的重构在第三方库,所以我们希望不改变这种状况。

Answer 1:

我认为你过于具体

更新 :原来的答案并没有直接的子选择保住孩子选择元素传播到孙子,等等。

我相信这个小提琴显示你想要什么。 它只是使用此代码选择表元素的角落,无论配置:

/* This works for everything */
.unit > :first-child > :first-child > :first-child, /* Top left */
.unit > :first-child > :first-child > :last-child,  /* Top right */
.unit > :last-child > :last-child > :first-child,  /* Bottom left */
.unit > :last-child > :last-child > :last-child    /* Bottom right */
{
    background: red;
}

当然,你可以使用table.unit如果你的.unit类放在其他元素,除了一个table有所缩小选择范围,但关键是要保住孩子选择模糊。



Answer 2:

您可以应对这样的情况下,THEAD:

tr td:first-child, tr th:first child {some styles}
thead + tbody tr td:first-child {revert the above styles}

不过,我不知道你会如何处理为TFOOT同样的情况。 您可能需要使用脚本。



Answer 3:

你不必改变你的表的结构。 他们符合HTML标准,存在使用干净的CSS让你问效果的解决方案。 使用:first-child:last-child在桌子上围件threadtbodytfoot允许你在整个表的角落只获取的细胞。 下面是详细信息。

*选择器简单地选择所有元素。 但>是指只适用于直接孩子的影响。 因此,我们获取所有上面列出的表包装元素。 一个没有更深的儿童tabletrtd受到影响。

要包括thtd ,我们再次使用*随着>获取表行的所有直接孩子,不管他们是否是th还是td 。 你可以代替两个类似定义选择。

.unit > *:first-child > tr:first-child > *:first-child,
.unit > *:first-child > tr:first-child > *:last-child,
.unit > *:last-child  > tr:last-child  > *:first-child,
.unit > *:last-child  > tr:last-child  > *:last-child {
    background: red;
}

我做了一个工作演示根据您提供关于这个问题的代码。

反正,你还没有告诉我们什么,你需要这个,有可能实现这一目标的更好的方法。 例如,如果你想提供圆角,可以适用于效果table的包装的div元素。



文章来源: Select only the first row in a table with css