For theming reasons I'd like to add a specific class at the "block" level to some of the blocks I'm generating with a custom module. I know there is a module block class, but I would rather like to do it directly in code (there is no need to change is afterwards).

I also know of hook_block_view_alter, but that does not seem to allow adding or editing classes.

Is it possible to add a class with to a block from within my module code? I'm using Drupal 7.


@flocondetoile's answer is OK, but the correct way is using drupal_html_class().

function YOURMODULE_preprocess_block(&$variables) {
  $variables['classes_array'][] = drupal_html_class('your-custom-class');

The function can be used from a module, or a theme.

| improve this answer | |
  • 1
    Thanks, this was exactly what I was looking for. One extra bit of information: this example will add the class to all blocks on the page, not just the blocks of your module. If you only want to target the blocks defined for a specific module, check the module name in $variables['block']->module. – Whiskey Aug 29 '12 at 7:41

Simply, you could use a preprocess function.

function YOURTHEME_preprocess_block(&$vars) {
  if ($vars['block_html_id'] ==  'ID-YOUR-BLOCK') {
    $vars['attributes_array']['class'][] = 'YOUR-CLASS';
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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