3 replies [Last post]
gautamz07
gautamz07's picture
Offline
Enthusiast
Last seen: 6 years 37 weeks ago
Timezone: GMT+5.5
Joined: 2014-04-24
Posts: 265
Points: 403

is :nth-child redundant and is :nth-of-type much better , definitive and maintanable after all ?

just wanted to know from you guys , which one of the 2 do you guys use ?

gary.turner
gary.turner's picture
Offline
Moderator
Dallas
Last seen: 2 years 13 weeks ago
Dallas
Timezone: GMT-6
Joined: 2004-06-25
Posts: 9776
Points: 3858

No

They fulfill completely different purposes. One counts off the children of a parent element, The other counts off the elements of a specific type.

Trivial example:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type"
          content="text/html; charset=utf-8">
    <title>
      Test document
    </title>
    <style type="text/css">
/*<![CDATA[*/
 
    body {
        background-color: white;
        color: black;
        font: 100%/1.25 sans-serif;
        margin: 0;
        padding: 1.25em; }
 
    p {
        font-size: 1em; }
 
    #ex1 p:nth-of-type(2) {
	color: red; }
 
    #ex2 > p:nth-child(2) {
	color: red; }
 
    /*]]>*/
    </style>
  </head>
 
  <body>
    <div id="ex1">
      <h2>
        This is an example of :nth-of-type(2)
      </h2>
 
      <p>
        p1 
      </p>
 
      <p>
        p2
      </p>
    </div>
 
    <div id="ex2">
      <h2>
        This is an example of :nth-child(2)
      </h2>
 
      <p>
        p1
      </p>
 
      <p>
        p2
      </p>
    </div>
  </body>
</html>

cheers,

gary

If your web page is as clever as you can make it, it's probably too clever for you to debug or maintain.

gautamz07
gautamz07's picture
Offline
Enthusiast
Last seen: 6 years 37 weeks ago
Timezone: GMT+5.5
Joined: 2014-04-24
Posts: 265
Points: 403

still feel that

ur right , its just that since nth-of-type selector is more specific and in most cases you see that people misunderstand nth-child() for nth-of-type , also i see very few use cases for nth-child .

gary.turner
gary.turner's picture
Offline
Moderator
Dallas
Last seen: 2 years 13 weeks ago
Dallas
Timezone: GMT-6
Joined: 2004-06-25
Posts: 9776
Points: 3858

Change the html

Modify the example like so:

    <div id="ex1">
      <h2>
        This is an example of :nth-of-type(2)
      </h2>
 
      <p>
        p1 
      </p>
 
      <blockquote>
	<p>embedded p</p>
 
	<p> another embedded p</p>
      </blockquote>
 
      <p>
        p2
      </p>
    </div>
 
    <div id="ex2">
      <h2>
        This is an example of :nth-child(2)
      </h2>
 
      <p>
        p1
      </p>
 
      <blockquote>
	<p>embedded p</p>
 
	<p> another embedded p</p>
      </blockquote>
 
      <p>
        p2
      </p>
    </div>

That someone does not understand the differences does not suggest using the inappropriate pseudo-class.

cheers,

gary

If your web page is as clever as you can make it, it's probably too clever for you to debug or maintain.