Tutorials

How to add the first and last CSS class to WordPress menu items

Looking for a way to add the first and last CSS class to your WordPress navigation menu items? Most website owners want to customize their navigation menu first and last items, they can easily do it by adding a custom CSS class to the first and last item of the menu. But the problem is if you rearrange the menu item then it won’t be one the first and last position.

So here in this article, we will guide you to add the first and last CSS class to customize the first and last item of your website navigation menu.

Customize the first and last items using class selectors

The first process to customize your navigation menu first and the last item is to use the CSS selectors. This process is one of the easiest processes but it won’t work for the older browser. So you need to make sure that you have to use the latest web browsers. Here you need to add some additional CSS. You can add your custom CSS to your theme style.css file or use the theme customizer option.

To use the theme customize option go to the Appearance > Customize and then move on to the Additional CSS option. Here you just need to add the following code snippets.

ul#navmenuid > li:first-child { }
ul#navmenuid > li:last-child { }

Don’t forget to replace the navmenuid with your actual navigation menu id.  In the first-child & last-child options select the first and last navigation menu id of your website.

wordpress menu

Customize the first and last items using a filter

The second way to style up your first and last navigation menu is to add a filter to your WordPress theme. In this method, you need to edit your function.php file. If you are not editing your functio.php file before then you can see this article to learn how to copy & paste code snippets into WordPress

You just need to add the following code in your website function.php file.

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');

Now we need to add some basic CSS formatting to our theme’s styel.css file to style the first and last item of the navigation menu.

.first a {font-weight: bold;}

.last a {font-weight: bold;

This will bold the first and last item of your navigation menu. If you rearrange the menu the style won’t change for the last and first item.

Wrapping Up

Following the process, you will be able to add the first and last CSS class to WordPress menu items. You can see our other articles to learn How to unpublish a WordPress Page

How to add Facebook Messenger chat to your WordPress website

Disable Automatic Update Email Notification in WordPress

We hope this article will help you. If you like this article please like our Facebook Page to stay connected.

You Might Also Like