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

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

23 hours ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

6 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

6 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

1 week ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago