How to add First and Last CSS class to Drupal blocks

If you’re a themer looking to style blocks when its the first or last block in the region, use the following code snippet.

/**
* Returns a list of blocks.
* Uses Drupal block interface and appends any blocks assigned by the Context module.
*/
function YOUR_THEME_block_list($region) {
  // Code referenced from Fusion Core theme.
  $drupal_list = block_list($region);
  if (module_exists('context') && $context = context_get_plugin('reaction', 'block')) {
    $context_list = $context->block_list($region);
    $drupal_list = array_merge($context_list, $drupal_list);
  }
  return $drupal_list;
}
/**
* Implements template_preprocess_block().
*/
function YOUR_THEME_preprocess_block(&$vars) {
  // Adds 'first' and 'last' class to blocks for styling.
  $block_count = count(YOUR_THEME_block_list($vars['block']->region));
  if ($vars['block_id'] == 1 || $block_count == 1) {
    $vars['classes_array'][] = 'block-first';
  }
  if ($vars['block_id'] == $block_count) {
    $vars['classes_array'][] = 'block-last';
  }
}

 

Leave a Reply

Your email address will not be published.