What does the :last-child selector do?
The :last-child selector in CSS targets the last element among a group of sibling elements within a parent. It’s a way to style only the last child element. For example, if you want to set a border line on a vertical list of items:
- Bananas
- Berries
- Apples
- Grapes
not:last-child selector
The :not(:last-child) selector in CSS allows you to style all child elements except the last one within a parent. For instance, if you you want to center a list of elements with a margin between them:
HTML
<ul class="demo-list demo-list-last-child">
<li>Bananas</li>
<li>Berries</li>
<li>Apples</li>
<li>Grapes</li>
</ul>
<ul class="demo-list demo-list-not-last-child">
<li>Bananas</li>
<li>Berries</li>
<li>Apples</li>
<li>Grapes</li>
</ul>
CSS
.demo-list {
list-style-type: none;
margin: 2rem 0;
padding: 0;
}
.demo-list-last-child li {
background: #F0F0F0;
padding: 2px;
border-top: 1px dotted #C06800;
}
.demo-list-last-child li:hover,
.demo-list-not-last-child li:hover {
background: #CFCECE;
cursor: pointer;
}
.demo-list-last-child li:last-child {
border-bottom: 1px dotted #C06800;
}
.demo-list-not-last-child {
text-align: center;
}
.demo-list-not-last-child li {
display: inline-block;
text-align: center;
border: 1px dotted #C06800;
padding: 1rem;
}
.demo-list-not-last-child li:not(:last-child) {
margin-right: 20px;
}