How to select all child except the first one in CSS?

When working with CSS selectors, you might sometimes end up with a requirement where you have to select and style all child elements except the first one.

One way to achieve this is to add a custom style to each of the child element except the first one. But that’s not an effective way of doing this as it will take more time and effort.

We can very easily achieve this using the :not and :first-child selectors in a combination. For example, if you want to select all paragraphs except the first one that are inside a div element, you can use div :not(:first-child) selector.

Select all child except the first one in CSS

Here is a fully working example that selects all paragraphs except the first one:

Example:

div p:not(:first-child){
    background-color: yellow;
}

Similarly, if you want to select all paragraphs except the last one, you have to use div p:not(:last-child). Try out the below example:

Example:

div p:not(:last-child){
    background-color: yellow;
}

I hope now you learned the art of excluding any specific element/child from the selection. With the :not selector, you can not only exclude the first or last child element but any specific child element that you want.

To do that we have to use to the :nth-child(N) selector which allows you to select any nth element from the document. The number N can be 1, 2, 3, 4, 5,….. up to n.

For example, If you want to select all paragraphs except the third one which are inside a div element you have to use div p:not(:nth-child(3)) selector. It means here N=3.

Here is a fully working example that does the same task:

Example:

div p:not(:nth-child(3)){
    background-color: yellow;
}