Drupal 8 - Adding CSS and JS Files

How to add custom stylesheets and scripts to Drupal 8 sites
Oktober, 2016
Author: 
larry e. lectric

I've been trying the entire afternoon to add my custom  stylesheets and javascripts to a new Drupal 8 site without any luck. There are several howto's floating around the web, explaining how to add custom css and js files to a Drupal 8 but none of them seemed to work in my case. Obviously I've been missing only a little detail. So let me share with you, how to add your own stylesheets and javascripts that are loaded on every page of your Drupal 8 site.

For this project I'm using Adaptive Theme, but basically this approach does not depend on the base theme.

Steps to add your css and/or js files:

  • Create the new stylesheets and Javascripts in a subfolder of your theme
  • Define a new library in your themes yourthemename.libraries.yml
  • Add a reference to your new library in yourthemes yourthemename.info.yml

Let's have a look at an example where we are going to add mystylesheet.css and myscript.js to our theme and load it on every page of this site. Our theme directory is called yourthemename.

  • Create the file public_html/themes/yourtheme/styles/css/mystylesheet.css
  • Create the file public_html/themes/yourtheme/scripts/myscript.js
  • Define a new library called global-styling in public_html/themes/yourtheme/yourtheme.libraries.yml and add the following code:

    global-styling:
      version: 1.x
      css:
        theme:
          styles/css/mystylesheet.css: {}
      js:
          scripts/myscript.js: {}
      dependencies:
          - core/jquery

  • Reference the new library global-styling in public_html/themes/yourtheme/yourtheme.info.yml and add the following code. The bold text is the one you're actually adding, the other lines (green) should already exist in your file. The regions depend on the theme you're using. As mentioned above, we're using Adaptive Theme in this case:

    name: Some theme name
    type: theme
    'base theme': at_core
    'subtheme type': adaptive_subtheme
    layout: site-builder
    description: 'Wohlfhlwege Theme der Naturfreunde International (base theme: at_core).<br /> Generated: Di 21st, Jun - 13:50'
    'alt text': 'Screenshot for Wohlfühlwege'
    tags: sub-theme

    libraries:
      - yourtheme/global-styling

    regions:
      leaderboard: Leaderboard
      header_first: 'Header first'
      header_second: 'Header second'
      navbar: Navbar

After adding those lines clear all caches. If you're working on the commandline just run drush cr.

This is all you need to do. If you added those lines and cleared the caches but your new files are still not being loaded, you might have a problem with the indentation. You definitly don't have to re-save your theme settings (from the design admin pages), all you need to do is clearing caches and reloading your page.