首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CSS“nth-of-type”和“first-of-type Selectors”-良好实践/整洁代码

CSS“nth-of-type”和“first-of-type Selectors”-良好实践/整洁代码
EN

Stack Overflow用户
提问于 2013-05-17 18:50:05
回答 3查看 412关注 0票数 0

我目前正在使用这个CSS选择器:

代码语言:javascript
复制
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列的do {}

有什么更好的方法可以做到这一点?是否有可能减少代码,使其更具可读性和简洁性?

逻辑是这样的:

代码语言:javascript
复制
if column number is not 1 then
    do some code
else    
    do something else
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-05-17 18:51:41

你绝对可以减少很多杂乱的东西:

代码语言:javascript
复制
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" */ }

请记住,列并不等于“<th>”,因为列也可以是列,此外,colspan属性可以使一个元素占据多个列。

您还可以使用这个有效的等效版本,它具有极其广泛的浏览器兼容性(包括IE >= 7):

代码语言:javascript
复制
td:first-child { /* "1" */ }

td { /* "not 1" */ }
票数 4
EN

Stack Overflow用户

发布于 2013-05-17 19:07:46

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

代码语言:javascript
复制
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 */
}
票数 2
EN

Stack Overflow用户

发布于 2013-05-17 19:01:30

您可以使用nth-of-type(n+2)表示法。jsFiddle

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16607201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档