I'm trying to add a custom CSS class to the <body> tag, How can I modify or pre-process the <body> tag to add the class body, Is it right to style the <body> tag with css file?


If html.html.twig does not exist in your current theme's template folder, go to /core/modules/system/templates folder.

Open html.html.twig file. Highlight and copy all code (CTRL + A then CTRL + C)

Go to your theme's template folder /themes/[yourtheme]/templates and create a new file called html.html.twig, open and paste (CTRL + V) the code you copied.

Change <body{{ attributes }}> to <body{{ attributes.addClass('my-class') }}>

Clear/Flush the cache to see changes.

  • Is different from the copy and past the html.html.twig file? – Mojtaba Reyhani Aug 26 '16 at 14:52
  • @MojtabaReyhani if it already exists, it may be different as some modification could've been made. All it means is that you just skip the copy paste part and just edit the html.html.twig and change to attributes part, if you already have a html.html.twig file in your theme's template folder. – No Sssweat Aug 26 '16 at 20:50

Alternatively, you could implement template_preprocess_html in your [themename].theme file.

function themename_preprocess_html(&$variables) {
  $variables['attributes']['class'][] = 'class-name';

See the documentation: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_html/8.2.x

  • 1
    Just for understanding, could you please describe where shall I put the 'body' and 'myclassname'. will it be like $variables['attributes']['body'][] = 'myClassNameForBody' – CodeNext Aug 4 '16 at 7:01
  • @CodeNext if you open html.html.twig you will see that the {{ attributes }} variable gets printed inside the body tag, as you can also see in the snipped of my answer. Therefore, you already know this affects the body. – No Sssweat Aug 5 '16 at 23:59
  • @NoSssweat, Thx for input. I got your answer, which is straight forward to understand. I would like to understand this way of doing. Suppose I want my <body> class class-name, Do I have to add @Josh's answer as it is provided or I have to modify something? If I do not have to modify then how it will address specifically to <body>? Again Thx. – CodeNext Aug 6 '16 at 8:36
  • 1
    @NoSssweat, Ok, I understand..Thanks you...So ultimately it is function themename_preprocess_html(&$variables) which does this job of placing the class-name in the body and that class name is saved in attributes array. Thx. – CodeNext Aug 6 '16 at 9:42
  • 1
    This is, to me, the preferred approach. – Kevin Aug 26 '16 at 13:23

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.