Here we will learn, How to include css file using phtml file instead of layout xml in Adobe Commerce (Magento 2).
1. Create Layout xml file. We have used default.xml file.
File: <magento-path>/app/code/Webkul/CallCssDemo/view/frontend/layout/default.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">
<body>
<referenceBlock name="head.additional">
<block template="demo.phtml" class="Webkul\CallCssDemo\Block\Demo" name="css_demo_custom_block_demo" />
</referenceBlock>
</body>
</page>
2. Now Create Respective Block Demo.php
File: <magento-path>/app/code/Webkul/CallCssDemo/Block/Demo.php
<?php
namespace Webkul\CallCssDemo\Block;
use Magento\Framework\App\Config\ScopeConfigInterface;
class Demo extends \Magento\Framework\View\Element\Template
{
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* This function will be used to get the css/js file.
*
* @param string $asset
* @return string
*/
public function getAssetUrl($asset)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$assetRepository = $objectManager->get('Magento\Framework\View\Asset\Repository');
return $assetRepository->createAsset($asset)->getUrl();
}
}
3. Create respective phtml file demo.phtml
File: <magento-path>/app/code/Webkul/CallCssDemo/view/frontend/templates/demo.phtml
<?php
$url = $block->getAssetUrl('Webkul_CallCssDemo::css/demostyle.css');
if ($url):
echo '<link href="'.$url.'" rel="stylesheet" type="text/css" media="all" />';
endif;
4. Create your css file demostyle.css
File: <magento-path>/app/code/Webkul/CallCssDemo/view/frontend/web/css/demostyle.css
/* add your custom css */
.minicart-wrapper {
float: left;
}
Now, this css file will be loaded on your Adobe Commerce (Magento 2) pages.
For any technical assistance, feel free to email us at support@webkul.com. Additionally, explore various options to enhance your store’s performance by visiting the Adobe Commerce modules section.
If you require expert help or want to develop custom functionalities, consider hiring Adobe Commerce Developers for your project.
Thanks.

Be the first to comment.