user2690563
user2690563

Reputation: 13

CSS 3 nth-child(n) doesn't work #table_id td a:nth-of-type(n)

I have:

<table id="table_id" > 
<tr>
<td><a href="/"><img src="http://images1.png""></a></td>
<td><a href="http://x.com" >xx</a></td>
<td><a href="http://y.com" >yy</a></td>
<td><a href="http://z.com" >zz</a></td>
</tr>
</table>

and selector to change the link color and style

Why this one works

#table_id td:nth-of-type(2) a
{
color:#fff;
text-decoration:none;
}

but not this one?

#table_id td a:nth-of-type(2) 
{
color:#fff;
text-decoration:none;
}

Upvotes: 1

Views: 210

Answers (2)

ddavison
ddavison

Reputation: 29102

It all can be explained if we define what these CSS selectors are doing.

First selector (working):

#table_id td:nth-of-type(2) a

Translates to:

Find me any element that has the id table_id. Anywhere under that, then find me the second occurence that is a <td> Then find me an <a> anywhere under that.

This selector matches because:

<[**table id="table_id"**]> 
  <tr>
    <td><a href="/"><img src="http://images1.png""></a></td>
    <[**td**]><[**a**] href="http://x.com" >xx</a></td>
    <td><a href="http://y.com" >yy</a></td>
    <td><a href="http://z.com" >zz</a></td>
  </tr>
</table>

Second selector (not working):

#table_id td a:nth-of-type(2) a

Translates to:

Find me any element that has the id table_id and then under that, find me any occurence of <td>, then under that, the second occurence of the type <a>. Finally, find an <a> under that.

This doesn't match because:

<[**table id="table_id"**]> 
  <tr>
    <[**td**><a href="/"><img src="http://images1.png""></a></td>
    <[**td**]>
      <a href="http://x.com" ></a>
      <[**a**] href="this matches. because it's the second nth-type">
        <[**a**] href="this is the actual element you'd be selecting with that selector."></a>
      </a>
    </td>
    <[**td**]><a href="http://y.com" >yy</a></td>
    <[**td**]><a href="http://z.com" >zz</a></td>
  </tr>
</table>

Upvotes: 1

mareoraft
mareoraft

Reputation: 3912

First we look at #table_id td:nth-of-type(2). With #table_id as the parent, td:nth-of-type(2) targets the 2ND TD child. That is, it targets

<td><a href="http://x.com" >xx</a></td>

But #table_id td a:nth-of-type(2) looks at td as the parent, and therefore targets the 2ND A child. However, every a in your code is the 1ST child of it's td, and therefore is not targeted.

Upvotes: 0

Related Questions