SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Jul 2010
    Mumbai, Maharashtra, India
    0 Post(s)
    0 Thread(s)

    Confusion with nth-of-type selector....

    Hello Everyone,

    Please consider below example:

    Here I can select first p and second p tags by using selectors "p:nth-of-type(1)" and "p:nth-of-type(2)" respectively.

    However in below example, I'm not able to select first label using ".label:nth-of-type(1)".

    <div class="row">
    <div class="icon">A</div>
    <div class="icon">B</div>
    <div class="label">1</div>
    <div class="label">2</div>
    <div class="label">3</div>

    If I use selector ".label:nth-of-type(3)", it works. Could any one please explain me why selector ".label:nth-of-type(1)" didn't work?

    Sanjay Maurya

  2. #2
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Melbourne, AU
    460 Post(s)
    8 Thread(s)
    nth-of-type(1) is the first of those five divs, but it doesn't have the class "label", so .label:nth-of-type(1) doesn't apply to any of those divs. Only the third div is both the third of its type and classed as "label".

  3. #3
    The CSS Clinic is open silver trophybronze trophy
    Paul O'B's Avatar
    Join Date
    Jan 2003
    Hampshire UK
    182 Post(s)
    6 Thread(s)
    It can be a little awkward to understand at fist but as Ralph points out nth-of-type starts at the first element in that sequence irrespective of what class you have added and then nth-of-type(3) counts down to the third one and if that third element has the class you specified then a match is made. If the third element doesn't have the class then no match is made.

    It does not look for .label and then count on from there. It always starts at the beginning but a match is only made if the nth element has the class you specified.

    Here's a demo that may make it easier to see.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    p { margin:0 }
    .test:nth-of-type(3) { background:red; }
    <h1>.test:nth-of-type(3) { background:red; }</h1>
    <div id="main">
    		<div class="test">div with class .test</div>
    		<div>div with no class</div>
    		<p class="test">p with class .test</p>
    		<p>p with no class</p>
    		<div class="test">div with class .test - this will be selected</div>
    		<div class="test">div with class .test</div>
    		<p class="test">p with class .test - this will be selected</p>

Tags for this Thread


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts