Are you willing 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.
So 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.
Contents
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.
We’ll show you two ways to style the first and last items of your navigation menu.
Styling First and Last Items Using CSS Selectors
The first 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.
To follow this method you’ll have to add code to your theme’s style sheet or the ‘Additional CSS’ section of the WordPress Theme Customizer.
You should start by editing your theme’s style.css file, or by navigating to Appearance » Customize and clicking on ‘Additional CSS’.
After that, you need to paste the following code snippet and then save or publish your changes.
ul#yourmenuid > li:first-child { }
ul#yourmenuid > li:last-child { }
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.
Styling First and Last Items Using Plugins
The second way to style your first and last navigation menu items differently is to add a filter to your theme.
You’ll need to add code to your theme’s functions.php file. If you haven’t done this before, then see our guide on how to copy and paste code in WordPress.
All you have to do is open your theme’s functions.php file then paste the following code snippet:
function wpb_first_and_last_menu_class($items) {
$items[1]->classes[] = 'first';
$items[count($items)]->classes[] = 'last';
return $items;
}
add_filter('wp_nav_menu_objects', 'wpb_first_and_last_menu_class'
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.
We hope this tutorial helped you learn how to add the .first and .last class to WordPress navigation menus.
If you have any issue on this, you can use our comment session or join our delegate on facebook to solve any issues related to WordPress and subscribe to our YouTube Channel for WordPress video tutorials.