How to add CSS to a single product in Shopify
I wanted to hide a specific widget on a single product’s page in my Shopify shop, but I couldn’t find a way to edit the CSS for just a single product.
Sure, I could apply the CSS to all products, but I didn’t want to affect the rest of my store.
Fortunately, there’s a pretty simple way to do it using some liquid code.
If you’re new to liquid, don’t worry I will share the exact bit of code I used. If you’ve ever used twig (the templating language), then you should recognise liquid because it’s pretty similar.
1. Add a product-specific CSS class to the body tag
We need a way to be able to write CSS to just target the HTML on a single product. The best way to do this is to somehow add the product’s ID into a CSS class that we can use later to target the CSS to just that product’s ID.
First, navigate to Sales Channels > Themes, then next to your active theme, select Actions > Edit Code.
Then select the file Layout > theme.liquid.
Within the file’s HTML, look for the line which starts with
{%- if product.id -%}product-{{ product.id }}{%- endif -%} |
So basically you’re adding the code above into the class=”” section, between the speechmarks and after any other code within the speechmarks. Make sure you add a space before to separate the added code from what’s already there.
So now, the line should look something like this:
<body class="template-{{ template | split: '.' | first }} {%- if product.id -%}product-{{ product.id }}{%- endif -%}"> |
Save the page.
Now, visit a product page on the frontend of your site. View source code using your browser’s tools (Right click > View Source if you’re using Chrome).
You should see a line that looks like the following:
<body class="template-product product-1849235111987" data-gr-c-s-loaded="true" style="overflow: visible; height: auto;"> |
Notice the product-1849235111987 class? You can use this to target anything on this specific product page with CSS.
2. Add your CSS
Next, still within the code editor, open the Assets > theme.scss.liquid file. This is your main CSS file (well, SCSS file actually) that contains all of the styling infromation for your store.
At the bottom of the file, add the following line:
body.product-1849235111987{/* Your CSS here */} |
Amend this line to include your actual product’s ID number and add in any custom CSS instead of the comment.
You will also probably want to be more specific with the targeting rather than the body tag itself. For example, the following below would change the colour of a buy button for just that single product:
body.product-1849235111987 .product-form__cart-submit{background-colour: #ff0000;} |
Hopefully, I’ve explained things well. It may seem tricky at first, but it’s really simple once you understand what’s going on. If you’re already familiar with code, then you’ll probably have no difficulty.
Feel free to ask any questions in the comments and I’d appreciate any advice!