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',
]
%}

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon