Generate random color gradient background

Generate random color gradient background

Written by Tina Hammar on Feb 5th, 2021 Views Report Post

When users fail to adhere to your imaginary design guide you need to arm yourself to keep the look you aimed for when creating your website.

In this article I'll share one of my favourite secret design weapons :)

The missing image

Let's pretend you made this astonishing blog grid: blogGrid.png

You'll be disappointed when users don't attach any cover images to their blog posts and your perfectly aligned grid falls apart.

Your options

  • A library with random background images?
  • Change the layout to a masonry grid?
  • Replace with a solid color?

Sure, they are all practical solutions, but I'd like to show you how you can generate random color gradients to fill the voids.

Random color generator

If you don't like gradients, you might settle with a solid color?

Laravel, php

In Laravel you can create a custom helper

if (!function_exists('randomHexColor')) {
    function randomHexColor(): string
    {
        return sprintf("#%06x", rand(0, 16777215));
    }
}

Javascript

You can add a function to the Window. colors.js

window.randomColor = () => {
    return '#' + Math.floor(Math.random() * 16777215).toString(16)
}

Random gradient generator

Create a Laravel helper

Create a custom helper in Laravel

if (!function_exists('randomGradient')) {
    function randomGradient()
    {
        $color1 = sprintf("#%06x", rand(0, 16777215));
        $color2 = sprintf("#%06x", rand(0, 16777215));
        $angle = rand(1, 360);
        $gradient = "background: linear-gradient({$angle}deg, {$color1}, {$color2})";
        return $gradient;
    }
}

In Controller, Livewire, Blade

Now that you have the helper you can use it in a blade file. Like in this example, the $url property can either come from a Laravel controller or a Livewire dynamic $attribute

//in Laravel controller or Livewire component
$url = $model->getSomeImageUrl();

If the image url is missing, we swap the background to a colored gradient in the blade file.

<div 
    class="bg-center bg-cover bg-no-repeat relative w-full"
    style="
        height: 200px; 
        @if(empty($url))
            {{ randomGradient() }} 
        @else 
            background-image: url('{{ $url }}')
        @endif
    ">
</div>

Javascript

You need to create a helper function somewhere. Example: colors.js

function randomHexColor() {
    return '#' + Math.floor(Math.random() * 16777215).toString(16)
}
window.randomGradient = () => {
    let color1 = randomHexColor()
    let color2 = randomHexColor()
    let angle = Math.round(Math.random() * 360)
    let gradient = 'linear-gradient(' + angle + 'deg, ' + color1 + ', ' + color2 + ')'
    return 'background: ' + gradient
}

Alpine

With AlpineJS and Laravel you can use the best of two worlds, mix Laravel blade directives and the method we tied to the window.

<div 
    x-data
    class="bg-center bg-cover bg-no-repeat relative w-full"
    style="height: 200px;
    @if(empty($url)) x-bind:style="window.randomGradient()" 
    @else x-bind:style="background-image: url('{{ $url }}')" 
    @endif
></div>

Vue

You can use the window.randomGradient() in Vue, similar to Alpine.

<div
    class="bg-center bg-cover bg-no-repeat relative w-full"
    style="height: 200px;
    v-bind:style="url == '' 
    ? { 'background': window.randomGradient() } 
    : { 'backgroundImage': 'url(' + url + ')' }
></div>

Change the color spectrum to match your site theme.

As you can see in the snippets we generate a random value between 0 to 16777215. That is because 16777215 == ffffff (white) and 0 is black in its decimal value.

This means that you can play with the values to find a spectrum that matches your site theme.

Hex to decimal converter

Php

In php you can find a #hex colors decimal value with hexdec()

hexdec("ffffff"); // 16777215 (white)
hexdec("cccccc"); // 13421772
hexdec("191919"); // 1644825
hexdec("000000"); // 0 (black)

Javascript

In javascript you get the decimal value via parseInt() if you pass the radix argument.

A number with a radix of 16 indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

We can create a javascript hexdec() method

function hexdec(hexString){
  return parseInt(hexString, 16);
}

//now you can test the same examples as in the previous php snippet
console.log(hexdec("ffffff")); // 16777215 (white)

Comments (0)