CSS selector to select the first and second table cells

Can someone help me determine which selectors I need to change the width of my columns globally in my two column table?

Using this, of course, select all the cells:

table td { width: 50px; } 

I want it:

 <table> <tr> <td style="width: 50px">data in first column</td> <td style="width: 180px">data in second column</td> </tr> <tr> <td style="width: 50px">more data in first column</td> <td style="width: 180px">more data in second column</td> </tr> </table> 

I would like to put the width specification in the stylesheet, and not enter the width implicitly for each tag. Which CSS selector will allow me to set the width of 50 pixels and 180 pixels accordingly?

+6
source share
3 answers

Yeah.

 td:first-child{ width:50px; } td:nth-child(2){ width: 180px; } 

or as suggested by Brainslav edit:

 td:nth-child(1) { width: 50px;} td:nth-child(2) { width: 180px;} 

link

+16
source

Try using class names in your markup and using colgroup . This is by far the least problem since you only define width in colgroup and are compatible with multiple browsers.

Eg.

 <table> <colgroup> <col class="colOne" /> <col class="colTwo" /> </colgroup> <tr> <td>data in first column</td> <td>data in second column</td> </tr> <tr> <td>more data in first column</td> <td>more data in second column</td> </tr> </table> /* CSS */ .colOne{ width: 50px; } .colTwo{ width: 180px; } 

See the script: http://jsfiddle.net/4ebnE/

One thing, however, colgroup deprecated in HTML5. But then again, HTML5 is not yet standardized, so you can make the call.

Oh, and it's possible to do without CSS if you want:

 <table> <colgroup> <col width="50"/> <col width="180" /> </colgroup> <tr> <td>data in first column</td> <td>data in second column</td> </tr> <tr> <td>more data in first column</td> <td>more data in second column</td> </tr> </table> 
+3
source

I think it is best to use css pseudo selectors:

 table tr td:first-child { width: 50px; } table tr td:last-child { width: 150px; } td { background: gray; } <table> <tr> <td>data in first column</td> <td>data in second column</td> </tr> <tr> <td>more data in first column</td> <td>more data in second column</td> </tr> </table> 

Here is a JSFiddle example: http://jsfiddle.net/scottm28/gGXy6/11/

Alternatively, you can also use CSS3: nth-child () selector

0
source

All Articles