Add CSS and JS to Admin pages

Components

Adding CSS or JS to admin pages is easy. Just create a new library, create CSS and JS files, and then attach the library in the hook_page_attachments() hook.

MY_MODULE.libraries.yml

admin_styling:
  version: VERSION
  css:
    theme:
      css/admin-styling.css: {}
  js:
    js/admin-script.js: {}

MY_MODULE.module

/**
 * Implements hook_page_attachments().
 */
function MY_MODULE_page_attachments(array &$attachments) {
  if (\Drupal::service('router.admin_context')->isAdminRoute()) {
    $attachments['#attached']['library'][] = 'MY_MODULE/admin_styling';
  }
}

About the Author

Goran Nikolovski is a senior developer with over 10 years of experience in web, app, and AI solutions. He founded this website to share his expertise, provide useful resources, and contribute to the broader developer community.

AI Assistant