Magento 2 Custom Layout – How to Add Body Class

classlayoutmagento2

I create custom page layout. In admin area select this layout:

Amin -> Products -> Categories -> MyCategory -> Design -> Layout

Q: How add css class to body tag?

My file:

app/design/frontend/{Vendor}/{theme}/Magento_Theme/page_layout/custom.xml

<?xml version="1.0"?>
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_layout.xsd">
    <update handle="1column"/>
    <!-- my references -->
</layout>

Tried, but not work:

<body>
    <attribute name="class" value="my-class" />
</body>
----------------------
<referenceContainer name="root" htmlClass="my-class" />
----------------------
<referenceContainer name="root">
    <argument name="css_class" xsi:type="string">my-class</argument>
</referenceContainer>

Update. PY Yick answer not work too (for me):

<referenceContainer name="root">
    <arguments>
        <argument name="css_class" xsi:type="string">my-class</argument>
    </arguments>
</referenceContainer>

Best Answer

 Page Layout XML

As far as I'm aware this isn't possible out of the box via page layout XML, the existing implementation is done via PHP (checkout the addDefaultBodyClasses() function here);

/**
 * Add default body classes for current page layout
 *
 * @return $this
 */
protected function addDefaultBodyClasses()
{
    $this->pageConfig->addBodyClass($this->request->getFullActionName('-'));
    $pageLayout = $this->getPageLayout();
    if ($pageLayout) {
        $this->pageConfig->addBodyClass('page-layout-' . $pageLayout);
    }
    return $this;
}

Layout XML

Just in case anyone ends up on this question for standard layout XML it can be done this way:

Add the following attribute inside the <body> tags.

<body>
    <attribute name="class" value="your-class"/>
</body>

If this doesn't work you may need to clear your caches?