The :last-child pseudo-class works just like :first-child, but it targets an element that is the last child of its parent. This is perfect for adjusting spacing or adding borders to the final element in a group.
Example 1: Removing Bottom Margin from the Last Paragraph
/* Selects the last <p> element inside its parent */
p:last-child {
margin-bottom: 0;
}
Explanation
This CSS snippet removes the bottom margin from the last paragraph element within any parent container, preventing extra space at the end of a block of text.
Example 2: Styling the Last List Item
/* Targets the last <li> in any list */
ul > li:last-child {
border-bottom: none;
}
Explanation
This code removes the bottom border from the last list item (<li>) in any unordered list, creating a clean, finished look.
Example 3: Adding a Footer to the Last Section
/* Applies a border to the bottom of the last section */
section:last-child {
border-bottom: 1px solid #ddd;
padding-bottom: 15px;
}
Explanation
Here, the last <section> element on the page gets a bottom border and some padding, visually separating it from any content that follows.
Example 4: Highlighting the Last Column of a Table
/* Styles the last <td> in every table row <tr> */
tr td:last-child {
text-align: right;
font-style: italic;
}
Explanation
This CSS targets the last table data cell (<td>) in each table row, right-aligning the text and making it italic, often used for summary figures.
Example 5: A Call to Action in the Last Div
/* Styles the last <div> inside a container with the ID 'cta' */
#cta div:last-child {
background-color: #ffc107;
padding: 10px;
}
Explanation
This rule selects the last <div> inside an element with the ID #cta and gives it a prominent background color and padding to draw attention.