Magento – the proper way of positioning/ordering CSS files in Magento 2

cssheadlayoutmagento2

In the Magento 2 DevDoc it says

To include a CSS file, add the <css src="<path>/<file>" media="print|<option>"/> block in <head> section in a layout file.

However it doesn't say how we can influence the order of our CSS files. And if we add CSS files this way in a custom theme which has a parent theme the result is that the files are added quite at the top of the <head> section with a lot of other CSS files below them, meaning their priority is quite low and we cannot easily override rules from the parent theme or extensions.

There were similar problems in Magento 1 and there were workarounds. Some were more clean others less.
What is the best way to order a CSS file of a custom theme at the bottom of <head> in Magento 2 – if possible complying the Magento 2 layout guidelines for custom themes?

Best Answer

Magento2 has no built-in mechanism for this so I decided to treat it as an opportunity to write my first Magento2 extension. The Quickshiftin\Assetorderer extension is now available on GitHub!

Once you have the extension installed you can specify an order attribute in your css XML tags.

<head>
  <css src="css/page/home.css" order="100"/>
</head>

You can also use the order attribute in layout XML files such as default_head_blocks.xml. Any css tags you don't specify an order for are treated as if they have an order of 1.

Related Topic