Skip to main content

Drupal 8/9/10: Adding CSS body classes based on the current user's roles

Learn how to add custom body classes so your CSS can target specific Drupal user roles

HTML source code of a random page.

Introduction

Sometimes it's useful to add body classes based on the current Drupal user's roles.

This article shows how to do this by adding or modifying a template_preprocess_html() implementation in your .theme or .module file. No twig modifications required.

Step 1: implement template_preprocess_html()

In your theme'sMYTHEME.theme file or your module's MYMODULE.module file, add the following preprocess function.

Be sure to replace 'MYTHEME' or 'MYMODULE' with the name of your theme or module.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $roles = \Drupal::currentUser()->getRoles();
  foreach ($roles as $role) {
    $variables['attributes']['class'][] = "role-{$role}";
  }
}

Assuming the current user has the administrator role, the body classes for each of the pages this user loads will now also contain:

role-authenticated
role-administrator

Step 2: add styles

You can now add styles targeted at specific user roles.

We use this technique to render administrative or debug-related styles that only specific roles can see.

One interesting use is highlighting all images with missing or empty alternative text descriptions:

.role-administrator img:not[alt],
.role-administrator img[alt=""] 
{
  border: solid red 2px;
}

Further reading