skip to main content

I was writing a post about my new Hugo website, and I wanted to describe the colours used on this site. I wrote the names of the colours, but names do not convey the colour very well. Can you imagine what the colour #714825 looks like? What about rgb(0, 100, 255)?

I thought it would be great if the reader could also see a preview of the colours. I could add images of the colours that I am describing, but that is a lot of work and not very flexible. This is what led me to write this Hugo shortcode. I followed the Hugo docs on shortcodes for reference.


The following code in markdown

This is a colour shortcode {{< colour "#ff0000" >}}.

renders as

This is a colour shortcode #ff0000.

This works with all valid CSS colour syntaxes, not just hexcodes. Here are some examples:

  • #714285
  • rgb(0, 100, 255)
  • hsl(37.1, 100%, 91.8%)
  • aquamarine


I created a file named colour.html in layouts/shortcodes, and added the following code in it. We can now access this code in any markdown file using the colour shortcode.

{{ $colour := .Get 0 | safeCSS }}
<code style="background-color: {{ $colour }};"> 
  <span style="
      color: {{ $colour }};
      filter:  grayscale(1) invert(1) contrast(100);
      {{ $colour }}

The shortcode takes in an argument: $colour. We use this parameter to set the text in the code tag, and we set both the text colour and the background colour to $colour. We then invert the colour of the text and increase the contrast to make the name of the colour legible. The end result is that the text is white if colour is bright, and black if it is dark.


This works well in most cases, but it has some limitations.

  • When the luminosity of the colour is close to 50% and the saturation is low, neither black nor white text has enough contrast with the chosen colour, and the text is not as legible. Example: hsl(180, 10%, 50%)

  • The text is not legible when the colour is transparent. This is because the text is transparent too, and does not have enough contrast with the background. Example: rgba(120, 0, 240, 0.3)

Alternate style

Here’s another style of previewing colours.

  • #714285
  • rgb(0, 100, 255)
  • hsl(37.1, 100%, 91.8%)
  • aquamarine

The text is always legible, but the colour preview is smaller.

Here’s the shortcode for this style:

{{ $colour := .Get 0 | safeCSS }}
<span style="display: inline-block;
    width: 1.6ch;
    height: 1.6ch;
    border-radius: 0.1rem;
    background-color: {{ $colour }};
    {{ $colour }}

Let me know if you liked this shortcode, and which style you liked more. Feel free to use this code in your site and share your implementation with me. If you have any suggestions to improve this code, share those with me too.