Better Way Of Changing Css Based On Value In Shopify?

- 1 answer

I am creating a colour swatch selection for my products in Shopify. The swatch only shows if the variant name is equal to 'Colour'. This is fine and working as should.

I am just wondering if there is a better way of assigning the swatch colour rather than manually typing in the hex codes for each colour name.

At the moment I have the following code in my product-template.liquid file.

 <label for="ProductSelect-option-{{ }}-{{ value | escape }}" id="swatch-{{ value }}"{% unless variant_label_state %} class="disabled"{% endunless %}/>

So if the colour value is set to Red then the output of the id would be swatch-Red. Now my question is, in CSS the only way I thought of currently is manually typing in:

#swatch-Red { background-color: red; } 

but I would have to do this for ALOT of colours. Can anyone think of a more efficient way of doing this? The other thing to keep in mind aswell is I have colours called 'Gunmetal' and 'Pewter'. These are dark and light grey's and obviously those colours are not recognised within CSS.

Any suggestions are appreciated!



There a few options here.

1) The bad one that many premium themes use

Use images for the colors that are equal to the name of the variant. So for example red and you will have an image called red.jpg in your asset folder.

I don't like this solution very much since you require the client to upload an image for each color and you fill your asset folder with a lot of images.


  • you can add multiply colors


  • you require the admin to enter the code editor to upload an image
  • you must create an image for each color
  • you clutter your asset folder with images
  • admin must call the images in a specific way

2) Not a great solution, but better than 1)

Create a navigation that where you can set the name of the color as the link title and the hex value as the link url.

This way with a little liquid you will be able to set the color to the swatch.


  • you can add multiply colors
  • you keep your asset folder clean
  • you don't create new images for each color
  • the admin doesn't need to modify the theme editor


  • you required the admin to enter the hex value by hand

3) Best approach

Create a section with blocks.

Each block will have a color field and text field. The text field will be the placeholder for the color name.

So when you loop your variants you take the color field value and apply it to the swatch.


  • nice and dynamic way to create additional colors
  • nice way to choose a specific color
  • you don't create new images
  • you don't clutter your asset folder
  • you don't require the admin to enter the editor


  • when there are too many colors it's hard to find the correct one