A common web development task is to apply a unique style to only the first child in css. Let’s see how we can do that.

Let’s assume we have the following html structure:

1
2
3
4
5
<div #my-list>
  <div>content 1</div>
  <div>content 2</div>
  <div>content 3</div>
</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.

1
#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

1
2
3
#my-list > div:first-child {
    ...
}

Wasn’t that easy? Now you should have no problem applying first child specific styles. As a side note, you can also use the last-child psuedo-selector in order to style the last child in your css.

You can read more about the first child selector in the w3 schools documentation.

If you enjoyed this content, check out the programming section for more awesome technical content.