An asset library is a bundle of CSS and/or JavaScript files that work together to provide a style and functionality for a specific component. They are frequently used to isolate the functionality and styling of a specific component, like the tabs displayed at the top of each node, into a reusable library. If you want to include CSS and/or JavaScript in your Drupal theme or module you'll need to declare an asset library that tells Drupal about the existence, and location, of those files.
Cascading Style Sheets (CSS) can be included in a Drupal site in various ways. Whether you want to include CSS files from a custom theme or an external library, you will need to understand the concept of asset libraries and how to use them to include CSS for your Drupal site. To add HTML attributes such as classes or IDs, you will need to know some Twig.
Example tasks
- Add CSS files from a theme or module to a Drupal site
- Add an external CSS library, such as a font or icon library, to a Drupal site
- Add static or dynamic attributes and classes in a Twig template file
Confidence
Drupal 8 introduced new concepts and methods for adding CSS to Drupal. These methods are now established and not likely to change, although tips and tricks may emerge over time. Resources labeled for Drupal 8 should work for Drupal 9.
Drupalize.Me resources
Learn what libraries are, how to define them, and how to attach an asset library. Use these concepts and skills to add CSS to your Drupal site.
External resources
- Adding stylesheets (CSS) and JavaScript (JS) to a Drupal theme (drupal.org)
- Official documentation for defining asset libraries.
- Modifying attributes in a .theme file (drupal.org)
- Learn how to use a preprocess function to alter the contents of an attributes variable.
- CSS in Drupal Coding Standards (drupal.org)
- To minimize friction when contributing to CSS, the front-end developers of the Drupal community have reached consensus about our coding standards for:
- Formatting CSS code
- CSS architecture, including goals, pitfalls and best practices
- Grouping rulesets into files
- To minimize friction when contributing to CSS, the front-end developers of the Drupal community have reached consensus about our coding standards for: