我有这样的 HTML 结构:
<section id="main-content" class="photo-grid">
<h2>Photos</h2>
<div class="col-1-4">
<a href="#">
<p>File 503</p>
<img src="#" />
</a>
</div>
<div class="col-1-4">
<a href="#">
<p>File 508</p>
<img src="#" />
</a>
</div>
<div class="col-1-4">
<a href="#">
<p>File 505</p>
<img src="#" />
</a>
</div>
<div class="col-1-4">
<a href="#">
<p>File 525</p>
<img src="#" />
</a>
</div>
<br clear="all" />
</section>
我想为不同的 .col-1-4 元素设置不同的 CSS 属性。我如何使用 :nth-child() 选择它们?
我已经尝试了 #main-content:nth-child(n)
和 .photo-grid:nth-child(n)
,但没有似乎有效。
最佳答案
您应该为此使用 nth-of-type
而不是 nth-child
,这实际上是说“选择的第 n 个子元素”之间的区别指定的元素' vs '选择作为指定元素的子元素的第 n 类型元素':
#main-content div:nth-of-type(1)
Demo Fiddle
其中1
为相关div
的序号(索引从1开始)
您应该将 nth-of-type
应用到目标元素的特定类型,您甚至可以将上述重点放在:
.col-1-4:nth-of-type(n)
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.
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.
关于html - 如何使用 nth-child() 选择一个 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23697364/