2

I have a table and I want to be able to assign specific styles within CSS to certain columns in the table: -

<table border="1">

<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>

</table>​

I want to be able to give the first 2 th only the style of text-align:left; and the remaining th = text-align:center;.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
pab
  • 971
  • 4
  • 17
  • 30

3 Answers3

4

The standard and direct solution :

th {
   text-align:center;       
}
tr th:nth-child(1), tr th:nth-child(2) {
   text-align:left;   
}​

The advantage of this notation is that it's easy to change it to apply for example to the fourth and sixth th instead of the first two.

Note that this supposes the availability of CSS3 in the browser.

If you want to be compatible with IE8, you might do it easily in javascript :

var ths = document.getElementsByTagName('th'); // replace document by your table if necessary    
for (var i=2; i<ths.length; i++) ths[i].style.textAlign="center";

or with jQuery :

​$('th').each(function(){
    if ($(this).index()>=2) $(this).css('text-align', 'center');
}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​);​
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

Do this

    th:first-child, th:first-child + th{
        text-align:left;
        }
th + th + th{
        text-align:center;
        }

live demo http://tinkerbin.com/B5Zi88Pp

Rohit Azad Malik
  • 31,410
  • 17
  • 69
  • 97
0

CSS3 way

th {
text-align:center;
}
th:nth-child(0), th:nth-child(1) { text-align:left; }​

CSS2 Way

th{
text-align:center;
}
th:first-child, th:first-child + th{
text-align:left;
}
Daljit
  • 685
  • 5
  • 12