In Drupal 7, there is a class like path-node-NID (with NID replaced by the node ID of the node being viewed) added to the <body> tag so we can easily add CSS styles to specific nodes. This is missing in Drupal 8.

How can I add the node ID as CSS class to the <body> tag?


In mytheme.theme file: add the below code.

function mytheme_preprocess_html(&$variables) {
  // Add node id to the body class.
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $variables['attributes']['class'][] = 'node-' . $node->id();

This will add "node-{{nid}}" class in body tag.

Another Option

You can try Node Class module as well.

Node Class is a simple module that allows users to add custom CSS classes to any node through the node/add interface.

| improve this answer | |
  • 1
    For new user of drupal, you have to replace mytheme_ in function name with the name of the theme, if the theme name is comets, then : function comets_preprocess_html() – Sébastien Gicquel May 17 '17 at 10:00
  • I was receiving an error when viewing revisions: "Error: Call to a member function id() on string in mybootstrap_preprocess_html() (line 14 of /home2/mysite/public_html/themes/mybootstrap/mybootstrap.theme)". I modified your code in accordance with some of the code in tamerzg's module (below, and that fixed my issue! I changed "if($node) {" to "if(is_object($node)) {" – hockey2112 Dec 3 '19 at 22:49

Drupal 8 is missing this core D7 functionality, but now there is a module for that, its called Body node ID class

| improve this answer | |

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.