I need to add some css classes to each list item in a menu block that I created. I thought I could accomplish this by using the following code:

function mytheme_preprocess_block(&$vars) {

  if ($vars['block_html_id'] == 'block-menu-block-7') {
    $i = 1;
    foreach ($vars['elements']['#content'] as $key => &$item) {
      // get each list item and add some css
      if (strpos($key, '#') === FALSE) {
        $item['#attributes']['class'][] = 'col-' . $i++;
        if ($i > 3) {
          $i = 1;

However when I try this, I do not see the new class being added when I inspect the element although it does look like it is being added with this code. What am I doing wrong? I am using Drupal 7 by the way.


2 Answers 2

function MYTHEME_preprocess_block(&$vars) {
  if ($vars['block_html_id'] == 'block-menu-block-7') {
    $vars['classes_array'][] = 'CSS_CLASS_NAME';

If you want to add a class to each individual item (li or/and a)use something like this:

function MYTHEME_menu_link(array $variables) {
  // replace MENU-MACHINE-NAME appropriately
  if ($variables['element']['#original_link']['menu_name'] == 'MENU-MACHINE-NAME') {
    // Add menu-li class to each li 
    $variables['element']['#attributes']['class'][] = 'menu-li';
    // Add menu-li-a class to each anchor link
    $variables['element']['#localized_options']['attributes']['class'][] = 'menu-li-a';
  return theme_menu_link($variables);
  • I need to add a class to each item (in this case an li element) and hence the foreach loop. I believe this just wraps then entire block with the given class.
    – user5013
    Oct 11, 2013 at 22:50
  • 2
    Then please be more specific, your questions said "I need to add some css classes to a menu block that I created" please revisit/edit your question
    – Victor
    Oct 12, 2013 at 3:01
  • I tried your suggestion and while I can see that this should work it doesn't in my case. There appears to be something that is overwriting the classes because my changes don't show up.
    – user5013
    Oct 18, 2013 at 16:13

You can use the Menu attributes module. Here is a quote about it (from the module's project page):

This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.

You should use this module when:

  • You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
  • You want to give a menu item an ID so you can easily select it using jQuery
  • You want to add additional classes or styles to a menu item

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.