Skip to content
Related Articles

Related Articles

How to pick a random color from an array using CSS and JavaScript ?
  • Last Updated : 19 Nov, 2019
GeeksforGeeks - Summer Carnival Banner

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:




<!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>

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
Recommended Articles
Page :