htmlcsscss-selectors

How to select a div with nth-child()?


I have HTML structure like this:

<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>

I want to set different CSS properties to diferent .col-1-4 elements. How can I select them using :nth-child()?

I've tried #main-content:nth-child(n) and .photo-grid:nth-child(n), but that doesn't seem to work.


Solution

  • You should use nth-of-type and not nth-child for this, which is effectively the difference between saying 'select the nth child element of the specified element' vs 'select the nth type of element which is a child of the specified element':

    #main-content div:nth-of-type(1)

    Demo Fiddle

    Where 1 is the number (index starts from 1) of the div in question

    You should apply nth-of-type to the specific type of element being targeted, you could even focus the above to:

    .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.