Sometimes you need to applying styling to only the first child element. Let’s see how we can do that.

Let’s assume we have the following html structure:

<div #my-list>
  <div>content 1</div>
  <div>content 2</div>
  <div>content 3</div>

Given this structure, we would need a selector that targets only the first child within the outer div.

Let’s take this a step at a time.

How To Select Children

First, let’s try and create a selector that can target any div contained within the outer div.

#my-list > div

In this example, we use the ‘>’ symbol in order to target only the “children” divs inside of the element with the id my-list. This lets you target all of the children, but what we really want is to target only the first child.

How To Select the First Child

To select only the first child, we only need to make a small modification to our previous statement and add the first-child psuedo-selector. Our final selector looks like this

#my-list > div:first-child {

That’s all there is is to it. Now you should have no problem applying first child specific styles.