I have created a Magento 2 widget that displays a list of categories, similar to the one shown in this guide. The widget outputs the correct HTML, so now I need to add some styling to it to make it look nice.

In my reading on the internet, I have found that I can tell Magento to load a CSS file

  1. under the default layout file, which I presume will make it appear on all pages, or
  2. in a layout file that is specific to a single layout handle (for example, catalog_product_view).

What I am not understanding is how I can tell Magento to ONLY load that CSS file if the widget is present on a given page. Obviously, I can simply hard-code the path to a CSS file in the widget template itself, but this seems hacky. It would also mean that Magento has no way to know to compile/minify that CSS file.

I found a similar question about Magento 1, but the only answer is suggesting to do the exact thing I want to avoid: Having to hard-code the CSS include in the template file.

Disclaimer: Some of my assumptions may be incorrect, so feel free to correct me accordingly.

  • Do you have a solution for this?
    – Akif
    Commented Apr 28, 2021 at 12:06
  • No, sorry. In the 4 years since I posted this, I've abandoned Magento entirely and now use Shopify as my platform of choice for new builds. Commented Apr 28, 2021 at 16:42

1 Answer 1


Within your custom widget module create the following file:


Add the following code to _extend.less:

@import 'widget/example.less';

Create your .less file here:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.