Reading list Switch to dark mode

    How to Add CSS File Links in Phtml File Magento 2

    Updated 23 February 2024

    Here we will learn, How to include css file using phtml file instead of layout xml in 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 magento pages. Thanks.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home