Adding classes to body and html tags
Image source: Joshua Brandenburg

Adding classes to body and html tags

December 07, 2015

In your Drupal 8 theme, you can add classes to the html and body tags within the preprocess_html function in your .theme file.

function THEMENAME_preprocess_html(&$variables) {
  /* Add class to html tag */
  /* Set the section class on the BODY tag. */
  $variables['attributes']['class'][] = 'my__special--class';

Notice, however that the method for adding a class to each one is different. Why?

dsm of attributes

If we look at a dsm() of each, you will notice that $variables['attributes']['class'] at this point is an array of classes, so we can just add a class to that array. $variables['html_attributes'] however is an object.

dsm of attributes with available methods

In the dsm output there a tab for “available methods”. In that list you will find the method addClass() that we are using here.