CSS exclude last sibling element
CSS Exclude Last Sibling Element
In front-end development, you often encounter situations where you need to style a group of elements but want to exclude the last sibling element. This article will discuss in detail how to achieve this using CSS.
1. Using the :nth-last-child() pseudo-class selector
The :nth-last-child() pseudo-class selector selects all sibling elements following a given element. By combining the :nth-last-child() pseudo-class selector with the :not() pseudo-class selector, we can conveniently exclude the last sibling element.
/* Exclude the last sibling element */
.element:not(:last-child) {
/* Set styles here */
}
In the code above, we use the :not(:last-child) selector to exclude the last sibling element and then set styles within it.
2. Example Code
Let’s use a simple example to demonstrate how to exclude the last sibling element using CSS.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exclude Last Sibling Element</title>
<style>
.item:not(:last-child) {
background-color: lightblue;
padding: 10px;
margin-bottom: 5px;
}
</style>
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
</div>
</body>
</html>
In the example above, we assign an element the class “item,” then exclude the last sibling element using the :nth-last-child() pseudo-class selector and set background color, padding, and margin.
3. Run Results
If you run the above example code in a browser, you will see something like this:
- Item 1
- Item 2
- Item 3
- Item 4
- Item 5
Each “item” element has a blue background, padding, and margin, except for the last one.
4. Summary
By using the :nth-last-child() pseudo-class selector in conjunction with the :not() pseudo-class selector, we can easily exclude the last sibling element and style other elements.