In this tutorial we will show how to add a custom body class to a specific page (or every page) in a Magento 2 store. 

The code provided in this article was tested on Magetno 2.1.0

Body clases in Magento

Magento adds classes to the <body> tag on every page to help the developers make custom designs per page.

If you go for example to a product page, and look at the <body> tag, you will see something like -

<body class="catalog-product-view product-fusion-backpack page-layout-1column"> ... </body>

The body classes of this page are: 

Now you can use any of those classes in you CSS files to add specific design changes to this page.

Adding a custom body class to a page

If you want to add a custom body class to some specific page (or to all pages), you can do this using a plugin:

Step 1: Create a basic plugin Myvendor/Mymodule

To create the basic plugin, create the following file - 


with the following content

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Myvendor_Mymodule" setup_version="1.0.0" />

and the following file - app/code/Myvendor/Mymodule/registration.php

with the following content - 


Step 2: Add a configuration in frontend/di.xml

In app/code/Myvendor/Mymodule/etc/frontend/di.xml add the following code:

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">

<type name="Magento\Framework\View\Result\Page">
<plugin name="myModuleResultPage" type="Myvendor\Mymodule\Plugin\Result\Page"/>


Step 2: Implement the plugin

Create the file app/code/Myvendor/Mymodule/Plugin/Result/Page.php

With the following content -

namespace Myvendor/Mymodule\Plugin\Result;

use Magento\Framework\App\ResponseInterface;

class Page
private $context;

public function __construct(
\Magento\Framework\View\Element\Context $context
) {
$this->context = $context;

public function beforeRenderResult(
\Magento\Framework\View\Result\Page $subject,
ResponseInterface $response

if($this->context->getRequest()->getFullActionName() == 'checkout_cart_index'){

return [$response];

The Result

Try going to checkout/cart page in your website. You should see the "my_custom_class" class added to the <body> tag.

If you want to add the body class to a different page, just change the "checkout_cart_index" to the full action name of the desired page. Or just remove the "if" statement, if you want to add your custom class to all pages.



Leave A Reply

Your email address will not be published.