简体   繁体   中英

How to select all the first td's in a table

Hi I would like to select only the first <td> ( td with the text "label" ) of every row in a table, if you have a simple html like:

<table>
  <tr><td>label</td> <td>value</td></tr>
  <tr><td>label</td> <td>value</td></tr>
  <tr><td>label</td> <td>value</td></tr>
</table>

I would like to assign for example a width of 10% only to the first <td></td> group with selector I DONT want to use a class.

I have tried the follow selectors:

table.widget tr:first-child td{
    width:10%;
    border:0;   
}

But that selector only will pick the first td of the first tr no all the TD's so I tried

table.widget tr td:first-child{
    max-width:10%;
}

Of course what I got is the selection of the first child of the TD . NOT the td itself

it's possible to accomplishing this?

One way:

table tr td:first-of-type {
background: lemonchiffon;
}

http://jsfiddle.net/PRrq5/2/

Your second selector is actually correct:

http://tinker.io/40f64

table.widget tr td:first-child {
    background: orange;
}

To select the first child of each td, the selector would be like so:

table.widget tr td :first-child { /* note the space after the td */
    // styles
}

It should be noted, however, that the OP's sample table does not have the widget class applied to it.

If your table is expressing a collection of key/value pairs, placing your label text within a th might be more appropriate:

http://tinker.io/40f64/1

table.widget th {
    background: orange;
}

<table class="widget">
  <tr><th>label</th> <td>value</td></tr>
  <tr><th>label</th> <td>value</td></tr>
  <tr><th>label</th> <td>value</td></tr>
</table>

Try this:

table tr td:first-child { color: red; }

Fiddle: http://jsfiddle.net/74MFH/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM