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-child | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |