6

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?

1
  • Drupal 8 is missing this core D7 functionality, but now there is a module for that, its called Body node ID class
    – tamerzg
    Aug 8, 2019 at 13:07

3 Answers 3

15

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 (is_object($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.

2
  • 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() May 17, 2017 at 10:00
  • 1
    To be extra careful, you could check if $node is a node rather than just an object with$node instanceof \Drupal\node\NodeInterface instead of is_object($node)
    – John
    Mar 22, 2022 at 16:13
0

Further to the comment made by @hockey2112, the accepted answer throws an error when viewing revisions. The code below is more reliable.

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(is_object($node)) {
     $variables['attributes']['class'][] = 'node-' . $node->id();
   }
}
0

For those you might still be looking for this on Drupal 9, you may check out this module: https://www.drupal.org/project/body_node_id_class

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.