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:
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        pick a random color from array
    </title>
</head>
  
<body style="text-align:center;">
  
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
      
    <h3>Pick a random color from array</h3>
  
    <h3 id="pick" style="color:red;">
        Sample Text
    </h3>
  
    <br><br>
  
    <button onclick="pickColor()">
        Click to change color
    </button>
  
    <script>
  
        // 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');
            x.style.color = random_color;
        
    </script>
</body>
  
</html>

chevron_right


Output:

  • 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.

full-stack-img




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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.