有一个包含两个 fieldset
的 HTML 结构,如下面的 jsfiddle 示例所示。以下 CSS 行
#aboutus > fieldset:nth-child(2) li {
text-align: left;
}
可以影响 jsfiddle 中第二个 fieldset
的元素,但是在页面上应该为结果添加这个:
#aboutus > fieldset:nth-child(4) li {
text-align: left;
}
没有第 4 个字段集,但仅在这种情况下将 text-align: left;
应用于对象 (li
)。
最佳答案
您想使用 nth-of-type
而不是 nth-child
,前者考虑元素类型,后者考虑其位置和资格。
Demo Fiddle
The :nth-of-type CSS pseudo-class matches an element that has an+b-1 siblings with the same element name before it in the document tree, for a given positive or zero value for n, and has a parent element. See :nth-child for a more thorough description of the syntax of its argument. This is a more flexible and useful pseudo selector if you want to ensure you're selecting the same type of tag no matter where it is inside the parent element, or what other different tags appear before it.
The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n, and has a parent element.
This can more clearly be described this way: the matching element is the bth child of an element after all its children have been split into groups of a elements each.
关于html - CSS nth-child() 工作奇怪吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24828796/