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

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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.