将表中的样式应用于 th 和 td 中的特定列 [英] Apply style in a table to specific columns within the th and td

查看:20
本文介绍了将表中的样式应用于 th 和 td 中的特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,我希望能够将 CSS 中的特定样式分配给表格中的某些列:-

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

我希望能够只给前 2 个 text-align:left; 和其余 th = text-align:center; 的样式.

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

推荐答案

标准直接的解决方案:

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

这种表示法的优点是很容易将其更改为适用于例如第四个和第六个 th 而不是前两个.

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.

请注意,这假设 CSS3 在浏览器中的可用性.

如果你想兼容IE8,你可以用javascript轻松做到:

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

或使用 jQuery :

or with jQuery :

​$('th').each(function(){
    if ($(this).index()>=2) $(this).css('text-align', 'center');
}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​);​

这篇关于将表中的样式应用于 th 和 td 中的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆