Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Code snippet that can be used to append css class to menu link in twig file in Drupal 8.

Question:

How to append css class to menu link item?

Solution:

You see that set classes directive in menu.html.twig ?

{%
  set classes = [
  'menu-item',
  item.is_expanded ? 'menu-item--expanded',
  item.is_collapsed ? 'menu-item--collapsed',
  item.in_active_trail ? 'menu-item--active-trail',
]
%}

This is where the magic happens and the classes array is built for all CSS classes to attach to your link item(s).

And this is also the place where you should add your additional CSS class that should be used in every link item, like so:

{%
  set classes = [
  'my-custom-css-class',
  'menu-item',
  item.is_expanded ? 'menu-item--expanded',
  item.is_collapsed ? 'menu-item--collapsed',
  item.in_active_trail ? 'menu-item--active-trail',
]
%}

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal, Laravel.

Web Posts

Search

Page Facebook