Paul Paul - 4 days ago 4
CSS Question

Assign styles to certain elements within a table with CSS


Possible Duplicate:

Apply style in a table to specific columns within the th and td




I have a table and I need to be able to assign different styles to different columns, I need: -


  1. The first two columns in the table header (header1 and header 2 to be given text-align:left; then all the remaining headers within the table header to be given text-align:center;

  2. Similar thing with the table rows, the first two for all rows in the table to be given text-align:left; then the rest of the tds given text-align:center;



So basically the first two columns throughout the table will be left, then remaining be centered??

`

<tr>

<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
<th>Header 5</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
<td>row 1, cell 3</td>
<td>row 1, cell 4</td>
<td>row 1, cell 5</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
<td>row 2, cell 3</td>
<td>row 2, cell 4</td>
<td>row 2, cell 5</td>

</tr>


‚Äč

Answer

Assuming your table has a class mytable:

.mytable td, .mytable th {
    text-align: center;
}
.mytable td:first-child, .mytable td:nth-child(2) {
    text-align: left;
}
.mytable th:first-child, .mytable th:nth-child(2) {
    text-align: left;
}

This can be written more compactly as:

.mytable td, .mytable th {
    text-align: center;
}
.mytable td:nth-child(-n+2) {
    text-align: left;
}
.mytable th:nth-child(-n+2) {
    text-align: left;
}
Comments