Skip to content
Related Articles

Related Articles

How to pick a random color from an array using CSS and JavaScript ?

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 19 Nov, 2019

The task is to pick a random color from an array using CSS. There is no way to do this using CSS only. CSS doesn’t support logical statements because CSS is purely deterministic (there is nothing like array etc in CSS). We can use client-side JavaScript to select a random color from the array.

Below Program illustrates the solution using client-side JavaScript:

<!DOCTYPE html>
        pick a random color from array
<body style="text-align:center;">
    <h1 style="color:green;">
    <h3>Pick a random color from array</h3>
    <h3 id="pick" style="color:red;">
        Sample Text
    <button onclick="pickColor()">
        Click to change color
        // JavaScript code to pick 
        // a random color from array
        function pickColor() {
            // Array containing colors
            var colors = [
                '#ff0000', '#00ff00', '#0000ff',
                '#ff3333', '#ffff00', '#ff6600'
            // selecting random color
            var random_color = colors[Math.floor(
                    Math.random() * colors.length)];
            var x = document.getElementById('pick');
   = random_color;


  • Before clicking on button:
  • After clicking on button:

Apart from above solution, We can use CSS preprocessors like SASS. Even if you use SASS you have to pre-process your stylesheets which means that you have to compile it.
To know more about SASS, click here.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!