In this post I am going to explain how to add attribute and class to the body tag in Magento 2

Magento 2 adds classes to the body tag on every page to help the developers make custom designs per page. In Magento 2 the controller name and page layout name added as a class to the body tag. So now I am going to explain you how you can add your own class to the body tag and how you can add new attribute to the body tag.

Add following code snippet in your layout file.

<?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>
        <attribute name="class" value="my-custom-class"/>
        <attribute name="custom-attr" value="attr-val"/>
    </body>
</page>

Now clear the cache and check for the result.

Add Custom Class and Attribute to the Body tag