About us

In Magento 2, you can add a CSS class to the <body> tag by creating a custom layout XML file. Here are the steps to do so:

Create a Custom Module (if not already done): If you don’t have a custom module already, you should create one. You can use the following commands to create a basic module:

php bin/magento module:status
php bin/magento module:create Namespace_Module

Replace Namespace with your module’s namespace and Module with your module’s name.

Create a Layout XML File: In your custom module, navigate to the view/frontend/layout directory if it doesn’t exist, create it. Inside the layout directory, create an XML file (e.g., default.xml) if it doesn’t already exist.

Example path: app/code/Namespace/Module/view/frontend/layout/default.xml

Add Your CSS Class to the Body: Inside the default.xml file, you can add the following code to add a CSS class to the <body> tag:

<?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="your-custom-css-class" />
    </body>
</page>

Replace "your-custom-css-class" with the CSS class you want to add to the <body> tag.

Clear Cache: After adding or modifying layout XML files, it’s a good practice to clear the Magento cache for the changes to take effect. You can do this using the following command:

php bin/magento cache:clean
  1. Refresh the Page: Once you have made these changes, the specified CSS class should be added to the <body> tag of your Magento 2 store’s frontend pages.

Remember to replace Namespace and Module with your actual module’s namespace and name, and customize the CSS class as needed to match your design requirements.