Colour is an essential part of any website’s design, as it can be key to creating a specific atmosphere and evoking an emotional response from your users. We often see colour in the form of company branding where businesses want to present themselves using a specific colour palette.
Playing with colour, such as randomising the colour of content, can make a website more dynamic, less predictable and more interesting for the user. It can be used in multiple types of content such as buttons, icons, text and backgrounds. The example I will work with is backgrounds, as I think they work seamlessly into a website’s design.
The example I have created uses a section containing multiple cards with different background colours. The way the solution works is by using CSS to assign a colour sequence to a series of elements and then assign the sequence to a specific number. For example, colour sequence one could go black, red, blue, green, orange. Using the CSS nth selector means you can choose to set every fifth element black, rather than just the first element. This way, the colour sequence can be repeated if you have more elements than colours.
Then create 5 (or as many as you like) colour sequences, each assigned to a number in the CSS selectors. From there, you need to assign some selector classes to the HTML you want to apply the colour randomiser to. You set the section class to “colour-randomiser”, then assign “colour-randomiser-repeater” to the element that appears multiple times, such as a card. Then, apply “colour-randomiser-element” to the specific element that changes colour, such as a button or div with a background colour.
Finally, a simple JavaScript solution selects a random number between 1 and 5 and assigns it to the section container. Depending on the number selected, it then applies one of the CSS colour sequences created previously. Now, you can reward your curious website visitors with dynamic and engaging content. Use the View Tool button below to view the GitHub gist with the full code sample, including a SASS alternative to CSS. Drop your examples in the comments below!
What’s the Chat?