Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');
}?????????????????????????????);?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...