Creating Useful CSS Hooks in Liquid

Many of us use the <body> class for CSS and JavaScript hooks and just like in WordPress it’s pretty easy to add a number of useful classes to our <body> element in Shopify.

Here are a few ideas that you might find useful placing in your main (or alternate) layout file:

Add the currently rendered template name to the body class

<body class="{{ template | handleize }}">

In this example, we are using template to return the name of the currently used template. Some examples of this are:

<body class="index"> <body class="product"> <body class="collection">

This can be really useful when you need to target a specific alternate template for example.

Add the currently rendered product handle to the body class

Building on this we may wish to add the current product handle to our body class. To keep things neat and tidy we can use an if statement to conditionally add the product handle only when we are viewing a product:

Note in this example we are using the Liquid filter handleize to ensure that the id or class that we add is URL safe and therefore easy to reference in our CSS and JS files. For example, it will turn a page title of “Blue Jeans” into “blue-jeans”.

Add the currently viewed collection’s name to the body class

For good measure, we could even add in a check for collections and add that too:

Thanks for subscribing

About the Author

Keir is based in the UK and works on the Marketing Team at Shopify. You can read his latest articles on his personal blog, listen to his podcast, follow him on Twitter, or check out his travel and everyday carry review site Leader of the Pack.