我将尝试找到一种方法来更改类的CSS样式,只有当它在具有4个TD的表格中时才更改。
代码可能更好地解释了我的问题。
HTML
HTML
<table class="myclass">
<tr>
<td>1 <span class="myclass2">xxx</span></td>
<td>2 <span class="myclass2">xxx</span></td>
<td>3 <span class="myclass2">xxx</span></td>
</tr>
</table>
<table class="myclass">
<tr>
<td>1 <span class="myclass2">xxx</span></td>
<td>2 <span class="myclass2">xxx</span></td>
<td>3 <span class="myclass2">xxx</span></td>
<td>4 <span class="myclass2">xxx</span></td>
</tr>
</table>
CSS
.myclass td:first-child:nth-last-child(3),td:first-child:nth-last-child(3) ~ td {
background-color:white !important;
}
.myclass td:first-child:nth-last-child(4),td:first-child:nth-last-child(4) ~ td {
background-color:red !important;
}
.myclass2 {
color:blue;
}
这里有一个JSFiddle链接:JSFIDDLE HERE
我的问题是,我想仅针对包含4个TD的表格中的元素更改“myclass2”的样式,而不是包含3个TD的表格。 这是否可能呢?
<table>
有四个单元格的方法是使用第四个或最后一个<td>
;而且目前还没有办法选择该第四个<td>
之前的兄弟节点。据我所知,这是一个需要以某种方式使用JavaScript解决的问题。 - David Thomastd:nth-last-child(4), td:nth-last-child(4) ~ td {/* css */}
应该根据您的需求为<td>
元素设置样式?尽管存在一个风险,即具有五个或更多<td>
元素兄弟的<table>
将导致这些样式出现问题:演示。 - David Thomas