Magento 2 - How to add custom css files into the head?

You don't need helper, you can using this code below in your layout:

<head>
    <css src="Namespace_YourModule::css/styles.css"/>
</head>

Try this steps.

  1. Create css file under this directory. app/design/frontend/Vendor/theme/web/css/customcss.css
  2. Create default_head_blocks.xml file if not exist at this path app/design/frontend/Vendor/theme/Magento_Theme/layout/default_head_blocks.xml

Put below code in default_head_blocks.xml

<?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>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
        <css src="css/customcss.css" />
    </head>
</page>

Hope this helps you!!


I found the solution myself.

In Layout xml file.

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="head.additional">
            <block class="Magento\Framework\View\Element\Template" name="block_name" template="custom_head.phtml" />
        </referenceBlock>
    </body>
</page>

In custom_head.phtml file

<link rel="stylesheet" type="text/css" media="all" href="<?php echo $_helper->getCSSFile()?>">