0

我目前正在使用这个 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
4

3 回答 3

4

你绝对可以减少相当多的混乱:

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" */ }
于 2013-05-17T10:51:40.747 回答
2

如果您专门针对整个第 1 列(假设您没有th在此处使用)

table tr td:nth-of-type(1) {
   /* Target 1st column */
   /* First td in each tr will be targeted here, and being more specific, 
      it will over ride the element selector defined below for each td element */
}

table tr td {
   /* Styles For The Rest */
}
于 2013-05-17T11:07:46.377 回答
0

您可以使用nth-of-type(n+2)符号。jsFiddle

http://www.w3.org/wiki/CSS/Selectors/pseudo-classes/:nth-of-type

于 2013-05-17T11:01:30.073 回答