CSS last-of-type
CSS last-of-type
In CSS, the :last-of-type
pseudo-class selector is used to select the last child of a certain type. This selector is very useful and can help us more precisely control the style of an element in style design.
Syntax
:last-of-type
The syntax of the pseudo-class selector is as follows:
selector:last-of-type {
/* styles */
}
Where selector
is the parent element of the element to be selected, :last-of-type
selects the last child element of a specific type under that parent element.
Sample Code
Example 1: Select the Last Paragraph Element
<!DOCTYPE html>
<html Tutorial">html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS last-of-type Example</title>
<style>
p:last-of-type {
color: red;
}
</style>
</head>
<body>
<p>geek-docs.com 1</p>
<p>geek-docs.com 2</p>
<p>geek-docs.com 3</p>
</body>
</html>
Output:
In this example, we select the last paragraph element and set its text color to red.
Example 2: Select the last list item
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS last-of-type Example</title>
<style>
li:last-of-type {
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
Output:
In this example, we select the last list item and make it bold.
Notes
:last-of-type
The pseudo-class selector can only select the last child element of a specific type within a sibling element, not the last child element of the parent element.- If no element meets the criteria, the
:last-of-type
pseudo-class selector will not take effect.
Summary
The :last-of-type
pseudo-class selector allows us to conveniently select and style the last child of an element of a specific type. This selector is very useful in real-world development, allowing us to more precisely control the styling of page elements.