我目前正在使用这个 CSS 选择器:
td:nth-of-type(2),td:nth-of-type(3),
td:nth-of-type(4),td:nth-of-type(5),
td:nth-of-type(6),td:nth-of-type(7),
td:nth-of-type(8),td:nth-of-type(9),
td:nth-of-type(10){
/* CSS rules... */
}
我想将规则应用于第 2-10 列,我宁愿说如果它不是第 1 列,则执行 {}
执行此操作的更好方法是什么?是否可以减少代码以变得更具可读性和简洁性?
逻辑是:
if column number is not 1 then
do some code
else
do something else
最佳答案
你绝对可以减少很多困惑:
td { /* "not 1" */
/*
Of course this applies to the first column as well
but you can override it with the next rule just below.
*/
}
td:not(:first-of-type) { /* more pure alternative for the above */ }
td:first-of-type { /* "1" */ }
请记住 <td>
不等于“列”,因为列也可能是 <th>
s 以及 colspan
属性可以使一个元素占据多个列。
您还可以使用这个具有极其广泛的浏览器兼容性(包括 IE >= 7)的等效版本:
td:first-child { /* "1" */ }
td { /* "not 1" */ }
关于CSS 'nth-of-type' 和 'first-of-type Selectors' - 良好实践/Tidier 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16607201/