Magento version: 2.0.0

How to add a class of style into tag? I think it is added in the xml, right?


Yes it's done via XML I reckon you can use the attribute tag for this

So in your layout, you can do:

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

An example in the default Magento install can be found here: https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Customer/view/frontend/layout/customer_account.xml

  • I added the htmlClass for <body> tag in the default.xml. then, i clear the cache but it not work for me.
    – Mike Zhang
    Mar 19 '16 at 10:29
  • @MikeZhang see my edit Mar 19 '16 at 11:30
  • 3
    Just a note on this functionality it is processed by vendor/magento/framework/View/Page/Config.php::addBodyClass() which strips out a lot of characters using regex and replaces them with - : $className = preg_replace('#[^a-z0-9]+#', '-', strtolower($className));
    – jzahedieh
    Feb 6 '17 at 15:25
  • +1 @jzahedieh, i.e. adding 'page--blocks' comes out on frontend as 'page-blocks' , annoying :/
    – 00-BBB
    Sep 18 '18 at 10:47
  • Also replaces underscores, why why why?!! :|
    – 00-BBB
    Sep 18 '18 at 10:52

In case you want to add a dynamic variable, eg. Store Code to the body class, you can take a look at the following example I made: https://github.com/samgranger/StoreCodeBodyClass


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.