How to select all children of an element except the last child using CSS?
Last Updated :
29 Mar, 2019
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 >
< 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 >
< 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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...