CSS :last-child Pseudo Class
Use the :last-child CSS pseudo-class for selecting and styling the last child among other sibling elements. Read about the pseudo-class and try examples.
The CSS :last-child pseudo-class selects the element if it is the last child among the other elements.
The :last-of-type selector can be used if the user wants to select and apply the style on the last paragraph whether or not it is the last child.
Info
Originally the selected element had to have a parent. In Selectors Level 4, this is no longer required.
Version
Syntax
CSS :last-child syntax
:last-child {
css declarations;
}Example of the :last-child selector:
CSS :last-child code example
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:last-child {
background-color: #1c87c9;
color: #ffffff;
}
</style>
</head>
<body>
<h2>Last-child selector example</h2>
<p>Lorem ipsum is simply dummy text...</p>
<p>Lorem Ipsum is simply dummy text...</p>
</body>
</html>Example of the last child of the <li> tag:
:last-child another code example
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
li:last-child {
background: #1c87c9;
}
</style>
</head>
<body>
<h2>:last-child selector example</h2>
<ul>
<li>Paris</li>
<li>Moscow</li>
<li>Rome</li>
</ul>
<ol>
<li>Paris</li>
<li>Moscow</li>
<li>Rome</li>
</ol>
</body>
</html>Example of the last child of the <p> tag:
:last-child second code example
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:last-child {
background: #8ebf42;
}
</style>
</head>
<body>
<h2>:last-child selector example</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</body>
</html>Example of :last-child for HTML lists:
Example of CSS :last-child Pseudo Class
<!DOCTYPE html>
<html>
<head>
<style>
ul li {
color: #8ebf42;
}
ul li:last-child {
border: 1px dotted #8ebf42;
color: #1c87c9;
}
</style>
</head>
<body>
<h2>:last-child selector example</h2>
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>
List Item 3
<ul>
<li>List Item 3.1</li>
<li>List Item 3.2</li>
<li>List Item 3.3</li>
</ul>
</li>
</ul>
</body>
</html>Practice
Practice
What does the :last-child CSS pseudo-class represent?