How to Pick a Random Color from an Array Using CSS and JavaScript

Last updated 3 weeks, 4 days ago | 40 views 75     5

Tags:- HTML JQuery CSS

In modern web design, adding a bit of randomness can make your page more dynamic and visually engaging.
One fun way to do this is by assigning random colors to elements every time a page loads or an event occurs.

Although CSS alone can't directly pick a random color from an array (because CSS is declarative),
we can easily combine JavaScript with CSS styling to achieve it!

In this tutorial, you’ll learn step-by-step how to:

  • Create an array of colors

  • Pick a random color

  • Apply it dynamically to HTML elements using CSS properties via JavaScript

  • See a complete working example!


Step-by-Step Guide


Step 1: Set Up Your HTML Structure

We’ll create a simple HTML page with a button and a box whose color will change randomly.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Random Color Picker</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>

  <div class="color-box">Click the button!</div>
  <button id="changeColorBtn">Change Color</button>

  <script src="script.js"></script>
</body>
</html>

✅ We have:

  • A div with the class color-box

  • A button that will trigger the color change


Step 2: Create the CSS Styles

Let's style the .color-box and the button a little.

/* styles.css */
body {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 50px;
}

.color-box {
  width: 200px;
  height: 200px;
  background-color: #ccc;
  margin: 0 auto 20px;
  line-height: 200px;
  font-weight: bold;
  color: white;
  transition: background-color 0.5s;
  border-radius: 12px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

✅ This gives the box a default color (#ccc) and a smooth transition effect when the background color changes.


Step 3: Create the JavaScript Logic

Now for the magic part: picking a random color and applying it.

// script.js

// Step 1: Define an array of colors
const colors = ["#FF5733", "#33FF57", "#3357FF", "#FF33A8", "#A833FF", "#33FFF6"];

// Step 2: Get references to DOM elements
const colorBox = document.querySelector('.color-box');
const changeColorBtn = document.getElementById('changeColorBtn');

// Step 3: Function to pick a random color
function getRandomColor() {
  const randomIndex = Math.floor(Math.random() * colors.length);
  return colors[randomIndex];
}

// Step 4: Event listener for button click
changeColorBtn.addEventListener('click', function() {
  const newColor = getRandomColor();
  colorBox.style.backgroundColor = newColor;
});

✅ How it works:

  • colors array holds your predefined color options

  • getRandomColor() randomly selects one color

  • On button click, we apply that color to the div


Full Working Example

Here’s how everything fits together:

HTML

<div class="color-box">Click the button!</div>
<button id="changeColorBtn">Change Color</button>

CSS

body {
  font-family: Arial, sans-serif;
  text-align: center;
  margin-top: 50px;
}

.color-box {
  width: 200px;
  height: 200px;
  background-color: #ccc;
  margin: 0 auto 20px;
  line-height: 200px;
  font-weight: bold;
  color: white;
  transition: background-color 0.5s;
  border-radius: 12px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

JavaScript

const colors = ["#FF5733", "#33FF57", "#3357FF", "#FF33A8", "#A833FF", "#33FFF6"];

const colorBox = document.querySelector('.color-box');
const changeColorBtn = document.getElementById('changeColorBtn');

function getRandomColor() {
  const randomIndex = Math.floor(Math.random() * colors.length);
  return colors[randomIndex];
}

changeColorBtn.addEventListener('click', function() {
  const newColor = getRandomColor();
  colorBox.style.backgroundColor = newColor;
});

Tips for Success

  • Use a nice color palette:
    Tools like Coolors or Adobe Color can help you pick beautiful color sets.

  • Smooth transitions:
    Always use CSS transition to make the color change feel smooth rather than jerky.

  • Accessibility:
    Make sure that your text color contrasts well with your random background colors for readability.

  • Randomness Tip:
    For more "natural" variation, you could also randomly generate RGB or HSL colors instead of using a fixed array.


Common Pitfalls to Avoid

  • Empty array:
    If your colors array is empty, getRandomColor() will fail. Always make sure it has values.

  • Hard to read text:
    Dark backgrounds need light text and vice versa — consider dynamically adjusting text color based on background brightness if needed.

  • Selecting wrong DOM elements:
    Double-check your querySelector or getElementById if you see errors like Cannot read property 'style' of null.


Conclusion

Combining a simple JavaScript randomizer with CSS styling lets you create vibrant, dynamic, and fun web experiences.
With just a few lines of code, you can dramatically improve your UI’s visual appeal!

This trick is perfect for:

  • Buttons

  • Backgrounds

  • Headers

  • Banners

  • Fun projects and games!


Next Level Challenge (Bonus)

Want to level up even more?
 Try randomly changing gradient backgrounds instead of solid colors!

See how to create random CSS gradient backgrounds next