CSS last child
Created By: chatGPT
:last-child
is a powerful pseudo-class selector in CSS that allows you to target the last child element of a parent. This can be particularly useful for styling elements differently based on their position within a hierarchy. You can apply it to various types of elements, including <div>
, <p>
, or any other block or inline element.p:last-child {
color: red;
font-weight: bold;
}
In the above example, all
<p>
elements that are the last child of their parent will be styled with red text and bold font-weight. This means if a <p>
is the last element in its container, it will receive these styles.ul li:last-child {
background-color: yellow;
}
You can also use
:last-child
in combination with other selectors to create more complex styles. For instance, if you want to style a specific type of element when it is the last child, you can do so like this:div > p:last-child {
margin-bottom: 0;
}
This example targets only
<p>
elements that are the last child of their parent <div>
and removes any bottom margin, effectively removing extra space from the last paragraph within each div.ul li:last-child {
border-bottom: none;
}
When designing a list, you may want to remove the border from the last item for a cleaner appearance. By using
:last-child
, you can easily achieve this while keeping the style consistent for all other items.table tr:last-child {
font-weight: normal;
}
If you're working with a table, applying
:last-child
to table rows can help you manage the weight of the text, ensuring that only the final row appears differently. Here, the last row would have a normal font weight, contrasting with the rest.section > div:last-child {
padding-bottom: 0;
}
In a section where you may have multiple divs, applying the last-child pseudo-class can help maintain a clean design by removing the padding only from the last div in that section, thus enhancing visual coherence.
li:last-child a {
color: blue;
}
Finally, if you want to change the link color of the last list item, you can use
:last-child
to apply that specific style. This can draw attention precisely where you want it in the list without affecting other links.nav li:last-child {
font-style: italic;
}