开发者

CSS selection of first column of first row of a table (excluding nested tables)

I'm having difficulty with CSS selectors and I hope someone can perhaps help me out here.

I have some HTML that looks like so:

<table class=myTable>
   <tr>
      <td>thi开发者_JAVA百科s is the td of interest</td>
   </tr>
   <tr>
      <td>
         <table>
            <tr><td>I don't want this td!</td></tr>
         </table>
      </td>
   </tr>
</table>

I am trying to apply a background image to the FIRST td of the FIRST tr. So I tried the following:

table.myTable tr:first-child td:first-child {
    background-image: url(someUrl.gif);
}

But this is also finding the first td of the first tr of the nested table. I've tried different combinations with > and +, but no luck. Anyone have any ideas?

Note: I'm aiming for a solution that is compatible with IE7+.


The selector you need is

table.myTable > tbody > tr:first-child > td:first-child

There is an implicit TBODY element in there, even though you don't have it in the code.


table.myTable > tr:first-child > td:first-child

The > means the tr that is a direct child of table


Not that speed is really a problem for the average website in this day and age, but, worth a note.

tags are slower to find than classes and classes are slower to find than id's.

So for simplicity and speed, how about just assigning an id to the element in question and applying a style to the id?


This work for me:

table.myClass > tbody:first-of-type > tr > td:first-child


table.myTable  > tbody tr > td:first-child

For first column.


table.myTable > tr:first-child > td:first-child

This code is difficult to support. Try the following instead:

<table class="myTable">
   <tr>
      <td class="verySpecialCell">this is the td of interest</td>
   </tr>
   <tr>
      <td>
         <table>
            <tr><td>I don't want this td!</td></tr>
         </table>
      </td>
   </tr>
</table>

or even

<table class=myTable>
   <tr>
      <td>
         <div class="verySpecialContent">
            this is the td of interest
         </div>
      </td>
   </tr>
   <tr>
      <td>
         <table>
            <tr><td>I don't want this td!</td></tr>
         </table>
      </td>
   </tr>
</table>


table.table td:nth-child(1) {text-align: center; font-weight: bold;}


The following code may help you,

HTML Code:

<table id="myTableId" class="myTableClass">
    <tr>
        <th>S.No</th>
        <th>Name</th>
    </tr>
</table>

CSS Code:

Using table id:

table[id="myTableId"] > tr:first-child > th:first-child{
}

Using table class:

table[class="myTableClass"] > tr:first-child > th:first-child{
}

or

table.myTableClass > tr:first-child > th:first-child{
}

or

table.myTableClass tr:first-child > th:first-child{
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜