Magento2 – How to Add New CSS File for a Module

magento2module

I'm trying add custom css file for my module namely Magento_Hello in magento2. In the module I've created new page and trying to add new custom css to that page.

Here is what I have done in app/code/Magento/Hello/hello_index_index.xml. ('hello' is the frontName of my module)

<?xml version="1.0" encoding="UTF-8"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Magento\Hello\Block\Hello" name="hello" template="success.phtml"/>
        </referenceContainer>
    </body>
    <referenceBlock name="head">
        <block class="Magento\Theme\Block\Html\Head\Css" name="magento-hello-css">
            <arguments>
                <argument name="file" xsi:type="string">Magento_Hello::css/custom.css</argument>
            </arguments>
        </block>
    </referenceBlock>
</page>

I'have added the css here app\code\Magento\Hello\View\frontend\web\css\custom.css

But I'm getting the error in system.log which says the 'magento-hello-css' element cannot be added as child to 'head', because the latter doesn't exist [] []

What I'm doing wrong? Can anyone help here?

Best Answer

In the latest beta version for Magento 2 there is no more head block.
The head, content and other blocks are defined as containers.

should remove the <referenceBlock name="head"> section and instead add this inside the <head> tag (where you added the page title)

<css src="Magento_Hello::css/custom.css"/>

so your <head> tag should look like this:

<head>
    <title>Hello World</title>
    <css src="Magento_Hello::css/custom.css"/>
</head>