🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Add Custom CSS Class Through XML File in Magento 2

By Sanjay JethvaUpdated on May 22, 2025 1 min read

Magento 2 is widely popular among the developers’ community, owing to its insane capability to customize and tweak the default configuration and code.

With increasing online stores and various types of businesses built with Magento 2 as the platform, there ought to be crazy requirements to fulfill customers’ expectations.

Recently, I found myself in the exact same scenario where I was required to add custom CSS class through XML file in Magento 2.

As it is not recommended to completely change the layout of the XML, I preferred the below solution:

Method to add custom CSS class through XML file in Magento 2:

The below example is to add CSS class in the product page:

Add the below code:

<?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>
        <referenceContainer name="product.info.media" htmlClass="custom col-lg-4 col-md-12 col-sm-12 product media" />
    </body>
</page>

Removing blocks and adding custom CSS/HTML classes are the usual requirements during store development. So, please bookmark this solution which is surely going to help you someday!

Feel free to share the solution with the Magento community via social media.

Thank You.

Also Read:

Sanjay Jethva Full Image
Article bySanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.