Themer-friendly menu link CSS classes for Drupal theme

What this code does is to give themers an easier way to style individual menu items in Drupal. For example, if you have a menu item title "Company Profile" and you want this link to be red colour, the following code (to be placed inside template.php file of your theme) will provide menu CSS class of <li class="... menu-company-profile">

/**
* Implements theme_menu_link().
*/
function YOUR_THEME_menu_link($vars) {
  $element = $vars['element'];
  $sub_menu = '';

  // Add classes to menu items for styling.
  $menu_class = strtolower(drupal_clean_css_identifier($element['#original_link']['title']));
  if ($menu_class) {
    $element['#attributes']['class'][] = 'menu-' . $menu_class;
  }

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options'] + array('html' => TRUE));
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

You can now apply your CSS style for this.

ul.menu li.menu-company-profile {
  color: red;
}

2 comments for 'Themer-friendly menu link CSS classes for Drupal theme'

Add new comment