How To

How to add Custom CSS Stylesheet using the block in Magento 2

In this tutorial, I am going to explain How to add Custom CSS Stylesheet using the block in Magento 2

Introduction:

Cascading Style Sheets better known as CSS, became an essential part of modern web design. Without CSS websites become plain text with no layout at all.

In this modern era where look and feel are everything, using CSS, developers can have full control over the layout allowing them to make precise section-wise changes and give a separate look. The most important part is the developer can add design flexibility and interactivity it brings to web development with cross-browser support. With growing competition in online eCommerce stores, if you want to make your design stand out from others, you must have to make use of CSS wisely.

Default, Magento allows you to build custom Extensions, CMS pages, block files, and so on to give a personalized touch to your Store Layout. But sometimes, you have to give different look to the particular page or portion where you need to specify your own CSS styles sheet that allows you to have full control and build an interactive layout other than default Magento.

Recently, we came across a requirement where we want to add our custom design inside our extension only when the extension is enabled. To do the same we have added our Custom CSS Stylesheet using the block in Magento 2.

Here is the solution to how we have done it.

Steps to add Custom CSS Stylesheet using the block in Magento 2:

Step 1: Move to the below path

app\code\Vendor\Extension\view\frontend\layout\default.xml

Add the below code

<!--?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>
        <referenceContainer name="after.body.start">
            <block class="Vendor\Extension\block\init"
                   name="css.file"
                   before="-"/>
        </referenceContainer>
    </body>
</page>

Step 2: Then, go to the following path

app\code\Vendor\Extension\block\init.php

Now add the code as follows

<?php

namespace Vendor\Extension\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Page\Config;

class Init extends \Magento\Framework\View\Element\Template
{
    protected $config;

    public function __construct(
        Template\Context $context,
        Config $config,
        array $data = [])
    {
        $this->config = $config;
        parent::__construct($context, $data);
    }

    protected function _construct()
    {
        $this->config->addPageAsset('Vendor_Extension::css/yourstyles.css');
    }
}

Conclusion:

That’s it, hope this code will help you to add your Custom CSS Stylesheet file using the block in your Magento 2 store. You can even use & customize this code according to your need for integrating stylesheet.

Add Dynamic CSS using Page Assets in Magento 2

Let us know if you are facing an issue while implementing this code.

Happy Coding!

Click to rate this post!
[Total: 15 Average: 4.1]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

Recent Posts

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

6 days ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

2 weeks ago

Managing Browser Events and Navigation in Shopify Remix: useBeforeUnload, useHref, and useLocation Hooks

Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…

2 weeks ago

Ultimate Guide to Hiring a Top Shopify Development Agency

Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…

2 weeks ago