【问题标题】:CSS: How to target a specific cell inside a table?CSS:如何定位表格中的特定单元格?
【发布时间】:2013-09-21 16:19:50
【问题描述】:

我有一个动态生成的表格,我需要为该表格第一行的第 5 个单元格设置不同的样式。

我可以通过以下方式设置第一行的样式:

//table.css

.mytable tbody tr:first-child { whatever styles I define.. }

或第 5 列通过:

.mytable tbody td:nth-child(5) { whatever styles I define.. }

我尝试将这两个选择器组合起来,使第一行第五列的单元格不同,但没有成功。我怎样才能做到这一点?

【问题讨论】:

    标签: css css-selectors html-table


    【解决方案1】:

    您可以简单地使用下面的选择器

    Demo

    Demo 2(多行)

    .mytable tbody tr:first-child td:nth-child(5) {
       /* Styles goes here */
    }
    

    说明:上面的选择器选择了第 5 个 td 元素,该元素嵌套在第一个 tr 元素下,该元素进一步嵌套在 tbody 下,tbody 进一步嵌套在具有类 .mytable 的任何元素下,但显然,tbody 将可以在 table 中使用,但如果您想具体说明,可以将 .mytable 更改为 table.mytable

    或者你可以使用

    .mytable tbody tr:nth-child(1) td:nth-child(5) {
       /* Styles goes here */
    }
    

    说明:同上,用nth代替first-child

    【讨论】:

    • 如果表没有theadtfooter,实际上不需要tbody
    • @FezVrasta 好吧,我不知道表结构是怎样的,我只是从他使用的选择器中做出来的
    • 谢谢你,工作就像一个魅力!我使这两个元素之间的组合复杂化了 tr:first-child td:nth-child(5)
    猜你喜欢
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2021-05-19
    相关资源
    最近更新 更多