Add custom css to a product page

If you need to add css rules specifically to your product pages then the best is to avoid adding those rules to all pages of your website.

You can achieve this but creating (or editing) a catalog_product_view.xml file inside /app/design/frontend/THEME_VENDOR/THEME_NAME/Magento_Catalog/layout or /app/design/frontend/THEME_VENDOR/THEME_NAME/Magento_Theme/layout.

Because of the way magento handle theme inheritance the xml code included on this file is added to the other existing xml code that is used to build up the product page in the frontend.

To add a css file put this into your catalog_product_view.xml:

<?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">
	<head>
            <css src="css/custom.css" rel="stylesheet" type="text/css"  />
        </head>
</page>

Then create a custom.css file and put it inside the /app/design/frontend/THEME_VENDOR/THEME_NAME/web/css folder.

And you are done (don’t forget to clear the cache 🙂 )!

Leave a Reply

Your email address will not be published. Required fields are marked *