Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 23 Jan, 2023
Improve Article
Save Article

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: 

html




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

Output:

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

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

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
Related Articles

Start Your Coding Journey Now!