1.

How is the nth-child() different from nth of type selectors?

Answer»

Both are pseudo-classes (Pseudo-classes are those keywords that specifies the special state of the selected ELEMENT). The nth-child() pseudo-class is used for matching elements based on the number that represents the position of an element based on the siblings. The number is used to match an element on the basis of the element’s position amongst its siblings.

For example, in the below piece of code, if we give nth-child(4) for the example class, then the 4th child of the example class is selected irrespective of the element TYPE. Here, the fourth child of the example class is the div element. The element is selected and a background of black is added to it.

.example:nth-child(4) { background: black; }<div class="example"> <p>This is a paragraph.</p> <p>This is a paragraph.</p> <p>This is a paragraph.</p> <div>This is a div.</div> <!-- 4th Element to select and apply style--> <div>This is a div.</div> <p>This is a paragraph.</p> <p>This is a paragraph.</p> <div>This is a div.</div></div>

The nth-of-type() pseudo-class is similar to the nth-child but it helps in matching the selector based on a number that represents the position of the element within the elements that are the siblings of its same type. The number can also be given as a FUNCTION or give keywords LIKE odd or even.

For example, in the below piece of code, if we give p:nth-of-type(even) for the example class, then all the even paragraph tags are selected within the example class and the style of background black is applied to them. The selected elements are MARKED in comments in the below code:

.example p:nth-of-type(even) { background: black; }<div class="example"> <p>This is a paragraph.</p> <p>This is a paragraph.</p> <!-- Select this and apply style--> <p>This is a paragraph.</p> <div>This is a div.</div> <div>This is a div.</div> <p>This is a paragraph.</p> <!-- Select this and apply style--> <p>This is a paragraph.</p> <div>This is a div.</div> <p>This is a paragraph.</p> <!-- Select this and apply style--> <div>This is a div.</div></div>


Discussion

No Comment Found