CSS 'nth-of-type' 和 'first-of-type Selectors' - 良好实践/Tidier 代码

标签 css css-selectors

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

相关文章:

css - less 中的嵌套样式,样式父级和子级

jQuery 选择器 : How do I select the outer div?

javascript - 更新状态不更新 View

html - Twitter Bootstrap 3 scrollspy 将无法工作

css - 你如何定义这个 CSS 选择器?

css - 使用 css 选择器 nth-of-type 不起作用

Android:根据主题/样式更改选择器字体大小

css - Nth Child Last child 其中奇数

html - 反转超过 70vh 的导航栏颜色 - html/css

css 动画只在第一次工作