Skip to main content

Drupal 8-9: Adding body css classes on your custom theme

This is how you add custom body css classes based on the "type" of the page (node or taxonomy page). Of course you can add whatever you want here. Even a css class for a specific taxonomy vocabulary or node bundle etc.

function mytheme_preprocess_html(&$variables) {

  $route = \Drupal::routeMatch();
  $route_parts = explode('.', $route->getRouteName());
  if (in_array('taxonomy', $route_parts)) {
    $variables['attributes']['class'][] = 'taxonomy-term--page';
  if (in_array('node', $route_parts)) {
    $variables['attributes']['class'][] = 'node--page';