Magento 2 : How to add custom css for adminhtml?

The question:

I need to add CSS file for Admin side in my custom module. How can I add this for Admin (back-end) only ?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

1 Create a module for example Vendor/Module, this _means a fully working module, including registration.php file etc.

2 Create a new file view/adminhtml/layout/default.xml in the module:

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
       <head>
         <css src="Vendor_Module::css/test.css"/>
       </head>
    </page>
  1. Add .css file in web folder as below path:

view/adminhtml/web/css/test.css

Run below commands and check.

php bin/magento cache:clean
php bin/magento setup:static-content:deploy

Optional – check css load order:

Note: css file load order might mean that your styles do not take effect, as styles.css gets loaded after these files.

This only works ~Magento 2.3 (tested on Magento 2.3.5).

For example: adding order to 999, ensuring that it _should be one of the last media=all items:

<css src="Vendor_Module::css/test.css order="999" />

For additional information (for instance for older versions) on ordering: See this question

Method 2

Magento 2 uses less file so you can also use less type as follows below step.

Create new file at Vendor/Module/view/adminhtml/web/css/source/_module.less

after that run below command from root directory and check

rm -rf var/view_preprocessed/
rm -rf pub/static/adminhtml
php bin/magento setup:static-content:deploy

Method 3

The accepted answer can still be improved. With default.xml you will add the file to * every * admin page. This may not be the desired behavior.

Use appropriate controller handle:

view/adminhtml/layout/your_controller_path.xml

System configuration handle:

view/adminhtml/layout/adminhtml_system_config_edit.xml

Method 4

TO ADD CUSTOM CSS OR JS IN ADMIN

Step 1: Create a module for example Vendor/Module

Step 2: Create a new file view/adminhtml/layout/default.xml in the module

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
layout="admin-1column" 
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/
page_configuration.xsd">

  <head>

    <css src="Vendor_Module::css/test.css"/>

    <script src="Vendor_Module::js/test.js"/>

  </head>

</page>

Step 3: Add .css file and add js file in web folder as below path

view/adminhtml/web/css/test.css

view/adminhtml/web/js/test.js


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment