将表中的样式应用于th和td中的特定列 [英] Apply style in a table to specific columns within the th and td
问题描述
我有一个表,我希望能够在css中为表中的某些列指定特定的样式: -
`
< tr>
< th>标题1< / th>
< th>标题2< / th>
< th>标题3< / th>
< th>标题4< / th>
< th>标题5< / th>
< / tr>
< tr>
< td>第1行,单元格1< / td>
< td>第1行,单元格2< / td>
< td>第1行,单元格3< / td>
< td>第1行,单元格4< / td>
< td>第1行,单元格5< / td>
< / tr>
< tr>
< td>第2行,单元格1< / td>
< td>第2行,单元格2< / td>
< td>第2行,单元格3< / td>
< td>第2行,单元格4< / td>
< td>第2行,单元格5< / td>
< / tr>
`
能够给第一个第2个只有文本对齐的样式:left;和其余的th = text-align:center;
标准和直接的解决方案:
th {
text-align:center;
}
tr th:nth-child(1),tr th:nth-child(2){
text-align:left;
}
此符号的优点是很容易将其更改为申请 http://caniuse.com/#feat=css-sel3rel =nofollow>浏览器中提供CSS3 。
如果您想要与IE8兼容,你可以在javascript中轻松做到:
var ths = document.getElementsByTagName('th') ; //如果需要,用表替换文档
for(var i = 2; i
或使用jQuery:
$('th')。each(function(){
if($(this).index()> = 2)$(this).css align','center');
});
I have a table and I want to be able to assign specific styles within css to certain columns in the table: -
`
<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>
`
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;
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');
});
这篇关于将表中的样式应用于th和td中的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!