在页面中,我有许多HTML表格,其中有许多列。我需要对它们应用不同的风格。所有的列将有不同的宽度,但在表格中它们将是相同的,我的意思是所有表格的第一列将相同,第二列和所有列相同。使用css自动将不同列样式应用于表列
CSS是应用在表上,但不是在列上,有没有一种方法,我只是添加CSS类,我可能没有把它们应用在HTML代码中,它们会自动应用。可能使用 伪列或其他方式?
在页面中,我有许多HTML表格,其中有许多列。我需要对它们应用不同的风格。所有的列将有不同的宽度,但在表格中它们将是相同的,我的意思是所有表格的第一列将相同,第二列和所有列相同。使用css自动将不同列样式应用于表列
CSS是应用在表上,但不是在列上,有没有一种方法,我只是添加CSS类,我可能没有把它们应用在HTML代码中,它们会自动应用。可能使用 伪列或其他方式?
如果你能使用支持CSS nth-child()
浏览器,你可以使用:
tr td:nth-child(even) {
background-color: #ffa;
}
在我使用:nth-child(even)
避免造型的第一td
元素(其中包含的行标题)上面的演示中,你可以,当然,包含行中的th
元素标题(这很可能是更多的语义正确的),或者样式的odd
列(或odd
td
元素),但不的:first-child
,该:not()
选择可用:
tr td:nth-child(odd):not(:first-child) {
background-color: #ffa;
}
如果你具有支持旧的浏览器,不支持:nth-child()
伪类限制,您可以使用相邻兄弟选择(虽然这是少维护):
td + td, /* styles the second td */
td + td + td + td { /* styles the fourth td */
background-color: #ffa;
}
td + td + td { /* styles the third td */
background-color: #fff;
}
Thoug它会更容易些类(即使只提供给odd
(或的even
)样式:
.even { /* styles the cells with the class of 'even' */
background-color: #ffa;
}
.even + td { /* styles the cell that follows the cell with the 'even' class */
background-color: #f90;
}
您也可以使用colgroup
和col
元素来定义类你列:
<table>
<colgroup>
<col class="first" />
<col class="second" />
<col class="third" />
<col class="fourth" />
</colgroup>
<thead>
<tr>
<th></th>
<th>Column one</th>
<th>Column two</th>
<th>Column three</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row one</td>
<td>row one, cell one</td>
<td>row one, cell two</td>
<td>row one, cell three</td>
</tr>
<tr>
<td>Row two</td>
<td>row two, cell one</td>
<td>row two, cell two</td>
<td>row two, cell three</td>
</tr>
</tbody>
</table>
用下面的CSS作为一个例子(注意这里没有理由不样式其他col
CL驴,我只是选择了不要在这个演示):
.second, .fourth {
background-color: #ffa;
}
参考文献:
您可以使用CSS3“第n”选择器,但它不适用于旧版浏览器。 所以你最好的解决方案是在页面加载后在javascript中应用更改(使用jQuery实例)。
$(function() {
$("table tr td:nth-child(n)").css('width', '100px');
});
,或者你可以添加一个类
$("table tr td:nth-child(n)").addClass("myWidth1");
,并在你的CSS
.myWidth1{ width: 100px }
确认表选择捕获所有表。
我不认为你可以没有任何服务器端编程或使用JavaScript。 – scaryguy
如何生成表格?您可以在打印时添加课程吗?如果不是,你可以使用CSS3选择器吗?还是只有CSS2? –