Select Child Element of Parent in CSS Using nth-child

By March 9, 2018 No Comments

This is an example of how to select a child of a parent element using CSS.  Most of the time you can add a class or id to the element and target with the normal methods, but when using plugins or other libraries it can get more complex than needed.  Some libraries generate the code dynamically and unless you’re willing to dig through the code for that function and update this is the next best solution.  It’s not ideal to modify the source code of many libraries as it handicaps your ability to quickly upgrade in the future.

Due to all of the above, he’s a simple way to target those elements where you don’t have a specific class or id using the nth-child method.  In this example I’m targeting the second “<p>” element on my page and setting the background color to red.

The CSS code below is how I’m targeting the second “<p>” element in my “<div>”.  My “<div>” has a class of “parentClass”.

.parentClass p:nth-child(2) {
            background: red;


Here’s the entire “<div>” with the class “parentClass”.

<div class="parentClass">
      <p>This is the first child.</p>
      <p>This is the second child.</p>
      <p>This is the third child.</p>
      <p>This is the fourth child.</p>
      <p>This is the fifth child.</p>


As you can see in the CSS code, I’m selecting the parent class and then counting down to the second “<p>” element and applying the style.

Here’s the entire page:


You can view a working demo of this here.

Leave a Reply