html - 如何使用 nth-child() 选择一个 div?

标签 html css css-selectors

我有这样的 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)

More on nth-child from MDN

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.

More on nth-of-type from MDN

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/

相关文章:

html - 使用 Golang 将已解析的 html 字符串从数据库显示到模板

css - 将水平导航栏的其余部分设置为另一种颜色?

html5 2 image inside section 只有CSS

html - Angular Material : Custom Form Field Control - move floating label (down)

css - 我可以合并 :nth-child() or :nth-of-type() with an arbitrary selector? 吗

html - 尺寸可变的CSS悬停图像裁剪

javascript - 立即显示对 HTML5 Canvas 的更改

css - PrimeNG 下拉列表 : Overriding the styles to hide input and label elements

css - 如何将样式应用于元素的所有子元素

javascript - 'animate()' 函数我的代码不起作用,但 'css()' 可以。怎么了?