CSS :last-child Selector

CSS :last-child selector selects an element that is the last 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:last-child selector will select every <p> element that is the last child of its parent and sets a yellow color background to it.

Example:

p:last-child{
   background: yellow;
}

In the following example, li:last-child selector selects and style every <li> element that is the last child of its parent:

Example:

li:last-child{
   background: yellow;
}

You can also select the last child of a specific parent element. In that case, you have to precede the :last-child selector with the parent element whose last child you want to select.

The :last-child selector in the following example selects only those <li> elements that are the last child of <ul> only. The <li> elements those are the last child of the <ol> will not be selected:

Example:

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

You can also select the child elements of the selected last child.

In the following example, the :last-child selector selects every <span> element that is inside the last child of the <div>:

Example:

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

CSS Syntax

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

:last-child{
   CSS Styles;
}

Browser Support

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

Selector
:last-child4.09.03.53.29.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.

    View all posts