关于html:为什么.class_name:nth-??child(even)计算没有.class_name的元素

Why .class_name:nth-child(even) counts elements without .class_name

本问题已经有最佳答案,请猛点这里访问。

:nth-child()计数的规则是什么?这仅仅是一个错误吗?

1
2
3
.info_row:nth-child(even) {
  background: orange
}
1
2
3
4
  Title
 
    Category:
    data

如果我将div.info_row包装在其他中或删除,则很明显,.info_row:nth-child(even)是使用进行计数的,而没有.info_row类。


您选择的是同一元素的第n个子元素,因此您可以
给它一个像.info_row :nth-child(even)这样的空格,这意味着它的第n个孩子,或者像.info_row >div:nth-child(even)

这样添加孩子div

1
2
3
.info_row >div:nth-child(even) {
  background: red;
}
1
2
3
4
  Title
 
    Category:
    data


您正在使用:nth-child()选择器,而您应该使用:nth-of-type()选择器:

1
2
3
.info_row:nth-of-type(even) {
  background: orange
}
1
2
3
4
5
6
7
8
  Title
 
    Category:
    data
 
 
    Category 2:
    data

说明

:nth-of-type()选择器选择与特定类型相对应的父元素的第n个子元素(即div标签)。另一方面,:nth-child()选择器选择父元素的第n个子元素,而不管其类型如何,因此也对h2元素进行计数。


.class:nth-??child(x)的意思不是"选择.class元素之间的数字x",而是"选择所有作为其父级数字x的.class元素"。

例如,div:first-child不会在以下位置选择div:

1
2
<p>foo</p>
bar

尝试:

1
2
3
.info_row div:nth-of-type(even) {
  background-color: orange;
}
1
2
3
4
  Title
 
    Category:
    data

1
2
3
.info_row div:nth-child(even) {
  background-color: orange;
}

1
2
3
4
  Title
 
    Category:
    data