3

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?

5

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.

  • 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

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.