CSS :first-child Selector

CSS :first-child selector selects an element that is the first child of its parent element and that parent element can be an anything like a <div>, <p>, <ul> or the <body> element itself.

For example, the following p:first-child selector selects every <p> element that is the first child of its parent and sets a yellow background to it.

Example:

p:first-child{
   background: yellow;
}

The following example selects and style each first <li> element of its parent:

Example:

li:first-child{
   background: yellow;
} 

If you want to select the first child of a specific parent element, you can do this by combining it with the :first-child selector.

The following example selects and style only those <li> that are the first child of the <ul> element only. The <li> that are the first child of the <ol> will not be selected.

Example:

ul > :first-child{
   background: yellow;
}

You can also select and style the child elements of the selected first child.

The following example selects each of the <span> that is inside of the first child of the <div> element:

Example:

div > p:first-child span{
   background: yellow;
}

CSS Syntax

The syntax of the :first-child selector is as follows:

:first-child{
   CSS Styles;
}

Browser Support

The number in each cell of the table specifies the first version of the browser that fully supports the :first-child selector.

Selector
:first-child4.07.03.03.19.6

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.