How To Add Custom CSS and JS in Magento 2
Magento 2 CMS allows the store owners to customize the core features in order to improve the store functionality as well as the customer experience.
Also, the custom themes are available for Magento 2 that adds attractive layouts and features in the default store, making it suitable for an online shop in today’s competitive market.
However, the unique business requirements may demand the developer to make customization in even a custom theme or simply customize a page.
In such cases, the below code to add custom CSS and JS in Magento 2 store can be helpful:
Method to add custom CSS and JS in Magento 2:
Create extension.css file and extension.js at app/code/Vendor/Extension/view/frontend(for admin adminhtml)/web/css/filename.css
Create default.xml file at app/code/Vendor/Extension/view/frontend/layout/ and in layout file, write the below code:
1 2 3 4 5 6 7 |
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> <css src="Vendor_Extension::css/extension.css"/> <link src="Vendor_Extension::js/extension.js"/> </head> </page> |
That’s it.
Note: There is an option to include CSS in template files, but it is recommended to avoid this practice as per the official Magento 2 DevDocs.
Any doubts? Mention them in the Comments section below and I’d be happy to help.
Feel free to share the solution with fellow Magento developers via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Pass Data From CMS Block to PHTML File in Magento 2
How to Implement Multiselect Filter For Order Status in Magento 2 Order Grid
Next