Magento2 – Add a custom CSS class to the body element

Magento2 – Add a custom CSS class to the body element

Sometimes we need to customize the whole layout. We can do this by adding a custom class over the body element. For example, in order to specify the text direction we often need to add a custom class to the body element. So based on styling the resulted class will be useful to customize the text direction.

To set the custom class use the attribute instruction to set HTML body tag name and value inside your layout xml file.

<body>
    <attribute name="class" value="my-custom-class"/>
</body>

A dynamic class can also be added by adding an Observer to the layout_load_before event. Create events.xml under etc/frontend folder. So it should look like : Vendor/Module/etc/frontend/events.xml

Add following snippet to the events.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="add_custom_class_event" instance="Vendor\Module\Observer\CustomClass" />
    </event>
</config>

Now add your CustomClass observer. Vendor\Module\Observer\CustomClass

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class CustomClass implements ObserverInterface
{
    /**
     * @var \Magento\Framework\View\Page\Config
     */
    private $config;

    private $customClassName = "my-custom-class";

    public function __construct(\Magento\Framework\View\Page\Config $config)
    {
        $this->config = $config;
    }

    /**
     * @inheirtDoc
     */
    public function execute(Observer $observer)
    {
        $this->config->addBodyClass($this->customClassName);
    }
}

This will add my-custom-class to the body element and will be visible on every page on frontend.

Add custom class to the body element

Leave a Reply

Your email address will not be published.