The best solution, of course, is to add it to the theme (preferably a sub-theme); however many times site builders and editors don’t have access to the codebase of a Drupal site.
To accomplish this, you can use the Asset Injector module. This module combines CSS Injector and JS Injector from Drupal 7 into one.
Let’s get started…
1. Install and enable the Asset Injector module.
Head over to https://www.drupal.org/project/asset_injector and either download the latest recommended version of the project (usually with a green background) or right-click on the .tar or .zip file and copy the location.
Install the Asset Injector module:
- Click Extend.
- Click Install New Module.
- If you copied the URL from the project page, paste it into the “Install from a URL” field and click Install.
- If you downloaded the module, click on the “choose file” button, select the file and click Install.
After the installation is done:
- Click Enable Newly Added Modules link.
- Check Asset Injector in the Development section.
- Scroll down and click “Install”.
2. Add Custom CSS
- Go to Configuration > Development > Asset Injector
- Click CSS Injector.
- Click “Add CSS Injector”
- Enter a label.
- Enter CSS code. No need to add
If you click Save Now using the example above, every H1 tag (page titles etc.) will be red in color.
You can limit where this CSS is applied! Assets can be restricted by:
- Content Type
- Node ID
- User Role
Note: These settings can be combined, requiring all or just one of them for the condition to be applied under, “Condition Requirements”.
- Click Save if you made any changes
- Click Back to Site to review the update!
- Go to Configuration > Development > Asset Injector > JS Injector and click “Add JS Injector”.
- Enter a label.
- Enter JS code.
- Select any of the Advanced Options required.
- Select any conditions (they are the same as CSS Injector).
- Click Save.
Note: These configurations use the Drupal 8 Entity API and therefore, all configurations are held in the database. This means they are exportable using Configuration Synchronization or custom module installs using yml files. This is great for multi-site installations where each site may have a few minor differences.
Also, at the time of this writing, the module does not work well with asset overrides, be it in settings.php, from the language system or other contributed modules.