CSS last one
CSS Last
In CSS, we often encounter situations where we need to style lists, elements, https://coder-cafe.com/wp-content/uploads/2025/09/images, etc. Sometimes we need to select the last element in a list and apply special styles to it. In these cases, we can use the last-of-type
pseudo-class or the nth-child
selector to achieve this.
Using last-of-type
The last-of-type
pseudo-class selects the last child of a parent element of a specified type. To use this pseudo-class, first determine the types of the parent and child elements. For example, if we have a ul
list with multiple li
elements, and we want to style the last li
element, we can do this:
<!DOCTYPE html>
<html>
<head>
<style> ul li:last-of-type {
color: red;
}
</style>
</head>
<body>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</ul>
</body>
</html>
In this example, we use the li:last-of-type
selector to select the last li
element under the ul
element and set its text color to red. When the page loads, the third element’s text color will change to red.
Using nth-child
>
In addition to the last-of-type
pseudo-class, we can also use the nth-child
selector to select the last element. The nth-child
selector selects child elements at a specific position under a parent element. If we want to select the last element, we can use this:
<!DOCTYPE html>
<html>
<head>
<style>
ul li:nth-child(n):last-child {
color: blue;
}
</style>
</head>
<body>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</ul>
</body>
</html>
In this example, we use the li:nth-child(n):last-child
selector to select the last li
element in the ul
and set its text color to blue. When the page loads, the text color of the third element will change to blue.
Summary
Whether using the last-of-type
pseudo-class or the nth-child
selector, you can easily select the last child of a parent element and set its style. In actual development, we can choose the appropriate method to select the last element based on our specific needs. The flexible use of CSS selectors allows us to better control the style of the page and provide users with a better visual experience.