10

Is it possible in Drupal 8, to add a CSS class to the <body> tag based on the current path alias?

2 Answers 2

14

In your theme, you can add the following code in template_preprocess_html:

$current_path = \Drupal::service('path.current')->getPath();
$path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
$path_alias = ltrim($path_alias, '/');
$variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($path_alias);
0
0

I created the module Path Alias Class.

This module add classes automatically from website Path and Path Alias. Also you can add Custom CSS. For example, if you have a node with title "Training" and NID is 77 then this module will automatically add these classes: training node-77.

This additional classes will help you easier to modify site appearance using CSS. Now you can styling the "training or node-77" page.

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.