I think you will agree when I say: running an online business is no easy task. You have to set up your website right, add products and then market the hell out of your business. It’s not for the faint of heart, more so for beginners. Even with all the effort you put in, your […]
Do you need to add custom styling to the first and last items of your WordPress navigation menu?
You could simply add a custom CSS class to the first and last menu items, but if the menu is rearranged, then those items will no longer be first and last.
In this article, we’ll show you how to add a .first and .last class that will style the first and last menu items even if the menu items are reordered.
Why Style the First and Last Navigation Items Differently?
In a past custom design project, we needed to add some custom styling to the navigation menu items of a WordPress website. This design in particular required different styling for the first menu item and the last menu item.
Now we could easily edit the menu and add a custom CSS class to the first and last menu item. But because we were delivering the project to a client, our solution had to work even if they rearranged the order of the menus.
In this tutorial, we’ll show you two ways to style the first and last items of your navigation menu. You can choose your preferred method from the list below:
This creates .first and .last CSS classes for your first and last navigation menu items respectively. You can use those classes to style the menu items.
For this tutorial, we’ll add the following basic CSS formatting to our theme’s style.css stylesheet to simply bold the first and last menu items:
.first a {font-weight: bold;}
.last a {font-weight: bold;}
Here you can see screenshots before and after we added the code to our demo site.
Method 2: Styling First and Last Items Using CSS Selectors
A second way to style the first and last menu items differently is to use CSS selectors. This method is simpler, but it may not work with some older browsers, such as Internet Explorer.
Note that you will need to replace ‘yourmenuid’ with the actual ID of the navigation menu. The selectors ‘first-child’ and ‘last-child’ select an element if it is the first and last child of its parent, which is the navigation menu.
For example, we used this code to bold the first and last navigation menu items on our demo site:
ul#primary-menu-list > li:first-child a {
font-weight: bold;
}
ul#primary-menu-list > li:last-child a {
font-weight: bold;
}
We hope this tutorial helped you learn how to add the .first and .last class to WordPress navigation menus.