How to select all children of an element except the last child using CSS?
When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.
Syntax:
element:not(:last-child) {
// CSS Style
}
Example 1: This example creates a navigation menu separated by right border except the last element.
<!DOCTYPE html> <html> <head> <title> Example to select all children except the last </title> <!-- CSS style to create nav bar --> <style> nav { margin: 30px; } nav a { text-transform: capitalize; text-decoration: none; color: rgba(60, 60, 60); font-family: sans-serif; padding: 10px 10px; margin-top: 30px; width: 150px; text-align: center; display: inline-block; } nav a:not(:last-child) { border-right: 5px solid greenyellow; } </style> </head> <body> <nav> <a href="#">Home</a> <a href="#">About</a> <a href="#">Blog</a> <a href="#">Geeksforgeeks</a> <a href="#">Articles</a> <a href="#">Contact Me</a> </nav> </body> </html> |
Output:

Example 2: This example creates a navigation menu and uses some CSS property except the last element.
<!DOCTYPE html> <html> <head> <title> Example to select all children except the last </title> <!-- CSS style to create nav bar --> <style> nav { margin: 30px; } nav a { text-transform: capitalize; text-decoration: none; color: rgba(60, 60, 60); font-family: sans-serif; padding: 10px 10px; margin-top: 30px; width: 150px; text-align: center; display: inline-block; border: 2px solid black; border-radius: 5px; } nav a:not(:last-child) { background-color:greenyellow; } </style> </head> <body> <nav> <a href="#">Home</a> <a href="#">About</a> <a href="#">Blog</a> <a href="#">Geeksforgeeks</a> <a href="#">Articles</a> <a href="#">Contact Me</a> </nav> </body> </html> |
Output:

Recommended Posts:
- How to select all child elements recursively using CSS?
- How to select an element by name with jQuery?
- How to set the value of a select box element using JavaScript?
- How to set the default value for an HTML <select> element?
- How to add options to a select element using jQuery?
- How to remove options from select element using jQuery ?
- PHP | SimpleXMLElement children() Function
- HTML | DOM children Property
- How to make flexbox children 100% height of their parent using CSS?
- CSS | :only-child Selector
- CSS | :last-child Selector
- CSS | :nth-child() Selector
- CSS | :nth-last-child() Selector
- CSS | :first-child Selector
- How to use a not:first-child selector in CSS?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



