Ways to Customize the img element in Shopify Themes

Ways to Customize the img element in Shopify Themes

This week we are going to have a look at the humble HTML img element.

When creating a Shopify Theme, you can add any number of images, in any format, and at any size to the assets folder within your theme directory. Typically, these images are used for backgrounds, sprites, and branding elements.

Referencing these images in a theme is very straightforward. Let’s assume we have a logo.png in our assets folder, we can output this image in any template using the following Liquid syntax:

{{ 'logo.png' | asset_url | img_tag: 'Logo' }}

This approach uses two Liquid filters to create a fully formed HTML img element. The first, asset_url, prepends the full path to the assets folder for the current store's theme, whilst the second, img_tag, uses this URL and creates an HTML img element complete with alt attribute. If omitted, the alt attribute will be blank. Here’s the end result:

<img src="//cdn.shopify.com/s/files/1/0222/9076/t/10/assets/logo.png?796" alt="Logo">

You’ll notice that the src attribute references the Shopify CDN (Content Delivery Network). Every image that you add, regardless of its type, will be pushed out to the Shopify CDN. You’ll never need to worry about the location of your images as the asset_url filter will work this out for you when the page is rendered. This approach also means that your themes are fully transferable from one store to another.

Adding classes to the img element

In the example above we added in the alt attribute. It’s also possible to add a further parameter which allows you to add classes to the img element. Here’s our example refactored:

{{ 'logo.png' | asset_url | img_tag: 'Logo', 'cssclass1 cssclass2' }}

This would result in the following output:

<img src="//cdn.shopify.com/s/files/1/0222/9076/t/10/assets/logo.png?796" alt="Logo" class="cssclass1 cssclass2">

More control

There will of course be occasions where you need a little more control over the markup. By simply omitting img_tag filter we can build up our markup as we wish.

Here’s an approach which would allow you to add your own attributes such as id:

<img src="{{ 'logo.png' | asset_url }}" alt="Logo" class="cssclass1 cssclass2" id="logo">

I hope you found these examples useful in your own theme building.

Want to learn more about Liquid and building with Shopify? Check out our full list of Shopify tutorials.

Photo of Keir Whitaker

About the Author

Keir is based in the UK and works on the Partner Growth Team at Shopify. You'll often find him at conferences and running workshops on Shopify theme building. You can subscribe to his newsletter, read his latest articles on Medium, listen to his podcast, and follow him on Twitter.

Grow your business with the Shopify Partner Program

Learn more