When the menu item becomes bold it changes the width of the menu item causing it to shift. This trick makes the menu item already the size of the bolded text so it won’t shift.
This uses a filter to create an attribute called ‘gtitle’ on each menu item that contains the same text as the menu item. We can then create a pseudo element (::before) on the menu-item that is bold but invisible. This will make the width of the element the size we want.
//* add title attribute to <a> in menu to allow for bold font without changing the size of a
add_filter( 'nav_menu_link_attributes', 'gtl_add_title_attrib_to_nav', 10, 2 );
function gtl_add_title_attrib_to_nav($attr, $item) {
$attr['gtitle'] = $item->title;
return $attr;
}
And for styling
// Probably want this selector to be more specific to the menu you want to affect
.menu-item a:before {
display: block;
content: attr(gtitle);
font-weight: bold;
height: 1px;
color: transparent;
overflow: hidden;
visibility: hidden;
}
I was doing this in Elementor which sets the anchor of a menu item with ‘display: flex;’ This causes the ::before pseudo element along with the text in the anchor to go side by side instead of the ::before element right under and increasing the width of the anchor correctly. I didn’t need the submenu icons so this css was also needed for this trick to work
// Probably want this selector to be more specific to the menu you want to affect
.menu-item a {
display: block;
}