How to Select All Except Last Child In CSS » CSS Not Last Child Example

css not last child select all except the last childWhen you want to format a list of items like when creating a menu or styling a menu you need to get the styles applied to each item. A common requirement is to use CSS not last child option to select all other items in the list apart from the last child. If you are looking for a good example of CSS not last child selection rule, this is post will guide you.

HTML Markup

In this post, I will use HTML menu to illustrate how you can select all items except the last child using CSS.

The following is an example of the HTML markup for the menu with 4 items :

<!DOCTYPE html>
<head>  
	<title>CSS Not Last Child </title>	
</head> 

<ul class="main-menu">
	<li>Home</li>
	<li>About</li>
	<li>Contact</li>
	<li>Members</li>
</ul>

<html>

As you can see in the markup we have 4 list items. We intend to select all the 3 first items (Home, About, Contact)  but leave the last one (Member)

 CSS Basic Styles

We need to add some basic styles to make the menu appealing and easier to demonstrate how to select all items apart from the last child.

The following are some basic styles to improve the appearance of this menu:

   <style> 
     
	  li {
		list-style: none;
		display: inline;
		padding: 20px;
		font-family: arial;
	}
   
   .main-menu {
		background: #2d7484;
		color: #fff;
		padding: 20px;
		max-width: 900px;
		
   }
   
   </style>

The menu now appears as shown below :  css not last child select

CSS Not Last Child Selection

To style all the first three items and not the last child you need to use the :not(:last-child) selector as follows :

.target:not(:last-child) {
	/* Styles for all other items except last item */
}

To illustrate how this works, we will apply an orange color to the other menu items except the last child shown on the image below:

css select all except last child

.main-menu :not(:last-child) {
    border: solid 1px #ddd;
    color: #ea9e12;
}

 

 CSS select all except last child

Similar Articles

Comments are closed.