Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
The :last-child Pseudo-class in CSS
The CSS :last-child pseudo-class selects an element that is the last child element of its parent. This powerful selector allows you to apply specific styles to the final element in a group without adding additional classes or IDs.
Syntax
selector:last-child {
/* CSS declarations */
}
Example 1: Styling Table Columns
The following example demonstrates how to style the last column of a table with a right border −
<!DOCTYPE html>
<html>
<head>
<style>
table {
margin: auto;
padding: 10px;
border: 3px solid #FFD700;
border-radius: 6px;
text-align: center;
border-collapse: separate;
}
td, th {
border-left: 2px solid black;
border-top: 2px solid black;
padding: 8px;
}
td:last-child, th:last-child {
border-right: 2px solid black;
}
th {
background-color: lightblue;
border-top: none;
}
caption {
background-color: purple;
caption-side: bottom;
color: white;
padding: 5px;
border-radius: 10px;
}
</style>
</head>
<body>
<table>
<caption>Student Scores</caption>
<tr>
<th colspan="4">Test Results</th>
</tr>
<tr>
<td>99%</td>
<td>95%</td>
<td>97%</td>
<td>92%</td>
</tr>
<tr>
<td>91%</td>
<td>98%</td>
<td>92%</td>
<td>90%</td>
</tr>
</table>
</body>
</html>
A styled table with a yellow border displays student scores. The last column in each row has a right border, creating a complete border around the entire table structure.
Example 2: Highlighting Last List Item
This example shows how to style the last item in an unordered list with a different background color and font −
<!DOCTYPE html>
<html>
<head>
<style>
ul {
max-width: 600px;
margin: 20px auto;
padding: 20px;
background-color: #f9f9f9;
border-radius: 8px;
}
li {
padding: 10px;
margin: 5px 0;
list-style: circle;
font-size: 1.1em;
}
li:first-child {
background-color: #FFE4E1;
font-family: cursive;
}
li:nth-child(2) {
background-color: #F0FFFF;
font-family: serif;
}
li:last-child {
background-color: #98FB98;
font-family: sans-serif;
font-weight: bold;
}
</style>
</head>
<body>
<h2>What is PHP?</h2>
<ul>
<li>PHP is a recursive acronym for "PHP: Hypertext Preprocessor".</li>
<li>PHP is a server side scripting language that is embedded in HTML.</li>
<li>It is integrated with popular databases, including MySQL, PostgreSQL, Oracle, and Microsoft SQL Server.</li>
</ul>
</body>
</html>
A list about PHP appears with three items. Each item has a different background color: light pink for the first, light blue for the second, and spring green with bold text for the last item.
Conclusion
The :last-child pseudo-class is essential for styling the final element in a container. It's particularly useful for tables, lists, and navigation elements where you need different styling for the last item.
Advertisements
