Drupal - CSS for specific pages

You can find totorial for adding specific CSS to specif page to the following links.

  1. Drupal 8 Theming Fundamentals, Part 1, but it is describing how to add specific CSS to front page.

  2. Drupal8 attaching libraries to specific pages, to add the specific CSS to specific node you need to follow tutorial on this page .

To give you example I am explaining with bartik theme for easy understanding.

I have created a css file cssfile.css and pasted at path css/cssfile.css Now this CSS file I want to use in one case to only front page and in otehr case to only specific node.

Step 1: Adding a library to the theme

Add the following code to bartik.libraries.yml.

css-filling: 
  css:
    theme:
      css/cssfile.css: {}

The library name I used is css-filling, but you can use other names.

Step 2: Adding the CSS styles to a specific page

Step 2a: Adding CSS styles only to the front page

The following code in the bartik.theme adds the library to the front page.

function bartik_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    $variables['#attached']['library'][] = 'bartik/css-filling';
  }
}
Step 2b: Adding CSS styles to a specific node

The following code adds the library only to a specific node.

function bartik_preprocess_node(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
    if ($node->id() == 3) {
      $variables['#attached']['library'][] = 'bartik/css-filling';
    }
  }
}

In the above code the important thing is path, bartik comes from the theme name and css-filling comes from step 1.


Most Drupal themes still provide enough classes on the body tag to allow you to target the front page separately from all others. Stable (the most basic of base-themes in Drupal 8 core) provides front on the front page and not-front on all others.

But you can load style sheets conditionally if that's important to your project. The complete details are available here, but the short version is that you can define a library in your theme and then attach the library in whatever html.twig file you need to ensure that libraries loads for:

{{ attach_library('mytheme/mylibrary') }}

Tags:

Theming

8