DEV Community

Cover image for Gradient Color Generator
Tilak Jain
Tilak Jain

Posted on

Gradient Color Generator

Hello World🌍,
Welcome to my new article. Today, we are going a beautiful Gradient Color Generator using HTML, CSS, Javascript and also use a bit of bootstrap for styling.
Let's get to work!

  • Out Boiler Plate
<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href=""> <!-- Bootstrap cdn -->
  <link rel="stylesheet" href="style.css"> <!-- Our css-->
  <title>Gradient Color Generator</title>
<!-- Our main section will go here -->
<script src="script.js"></script> <!-- our js -->
Enter fullscreen mode Exit fullscreen mode
  • Our main section
    <div class="container">
      <div id="hex-colors">
        <h1>Generate Beautiful Gradient Colors</h1>
        <h2>background: linear-gradient(to right, #<span id="hexcode1">ffffff</span>, #<span id="hexcode2">ffffff</span>);
        <button id="submit" class="btn btn-light">Click Me</button>
Enter fullscreen mode Exit fullscreen mode

We have some bootstrap classes in our main section.
But, we have to give it some basic style.
So, here goes:

  • Our CSS (style.css)
  width: 95%;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;

  width: 100%;
  text-align: center;

#hex-colors h1, h2{
  font-size: 2rem;
  text-transform: uppercase;

#hex-colors h2{
  margin-top: 15%;
  text-transform: lowercase;
Enter fullscreen mode Exit fullscreen mode
  • Our js (script.js)
document.querySelector("#submit").addEventListener("click", () => {
    var hex_numbers = ["0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D", "E", "F"];
    var hexcode1 = "";
    var hexcode2 = "";
    var random_index = 0;

    for(let i = 0; i < 6;i++){
      random_index = Math.floor(Math.random() * hex_numbers.length);
      hexcode1 += hex_numbers[random_index];
      random_index = Math.floor(Math.random() * hex_numbers.length);
        hexcode2 += hex_numbers[random_index];
    } = `linear-gradient(to right, #${hexcode1}, #${hexcode2})`;
    document.querySelector("#hexcode1").textContent = hexcode1;
    document.querySelector("#hexcode2").textContent = hexcode2;
Enter fullscreen mode Exit fullscreen mode

See the example below:

What to do after this:
1.You can add more styling
2.You can also make a copy button(that copies the background code)

Did you find it useful?
Comment down your thoughts! Don't forget to give it a heart and follow for more.
See you soon

Discussion (0)