如何选择一行中的第一个TD元素

时间:2012-08-29 06:57:58

标签: html css css-selectors

我有一些表格。 我想创建一个CSS,允许我以递归方式更改TD行中第一个TR元素的颜色,仅适用于具有类mytable的表。

你能给我一个CSS样本吗?感谢

<table class="mytable">
                <tr>
                        <td>Event Title:</td><!--Change color here-->
                        <td>{EventTitle}</td>
                </tr>
                <tr>
                        <td>Start date:</td><!--Change color here-->
                        <td>{DateTimeStart}</td>
                </tr>
                <tr>
                        <td>End date:</td><!--Change color here-->
                        <td>{DateTimeEnd}</td>
                </tr>
        </table>

6 个答案:

答案 0 :(得分:3)

为此,您可以使用:first-child 属性。写得像这样:

.mytable td:first-child{
 color:red;
}

答案 1 :(得分:2)

使用CSS“first-child”元素:http://www.w3schools.com/cssref/sel_firstchild.asp

所以可以这样做:

.mytable td:first-child {
   something here
}

答案 2 :(得分:0)

正如@sandeep所写,你可以使用first-child来实现目标。如果可能的话,更好的方法是在第一个td中添加一个类名。如果这应该是标题,您可能还想使用th代替td

答案 3 :(得分:0)

Sandeep有正确的想法,但你似乎要求一个更具体的风格规则。试试这个:

table.mytable td:first-child {}

答案 4 :(得分:0)

:first-child在IE中不起作用,一种实用的方法是更改​​这些td,您要将背景应用于th,然后设置样式

答案 5 :(得分:0)

你可以试试这个:

HTML

<table class="mytable">
                <tr>
                        <td>Event Title:</td><!--Change color here-->
                        <td>{EventTitle}</td>
                </tr>
                <tr>
                        <td>Start date:</td><!--Change color here-->
                        <td>{DateTimeStart}</td>
                </tr>
                <tr>
                        <td>End date:</td><!--Change color here-->
                        <td>{DateTimeEnd}</td>
                </tr>
        </table>

CSS

.mytable tr td:first-child{
 color:red;
}

http://jsfiddle.net/hrBAn/1/