DEV Community

loading...
Cover image for Random Hex Color Code Generator | HTML, CSS & JavaScript

Random Hex Color Code Generator | HTML, CSS & JavaScript

stackfindover profile image Stackfindover ・2 min read

Hello guys in this tutorial we will create random hex color code generator Using HTML CSS and JavaScript

First we need to create two files index.html and style.css then we need to do code for it.

Step:1

Add below code inside index.html


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Random Hex Code Generator</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap" rel="stylesheet">
</head>
<body>
  <div class="flex-row-outer">
    <div class="flex-row">
      <span id="hexCode">#000000</span>
      <button class="colorBtn" onClick="GenerateCode()">Generate</button>
    </div>
  </div>
  <script type="text/javascript">
    let body = document.querySelector("body");
    let hexCode = document.querySelector("#hexCode");
    body.style.backgroundColor = hexCode.innerText;

    function GenerateCode() {
      let RandomColor = "";
      let Char = "0123456789abcdefghijklmnopqrstuvwxyz";

      for(i = 0; i < 6; i++) {
        RandomColor = RandomColor + Char[Math.floor(Math.random() * 16)];
      }
      hexCode.innerText = "#" + RandomColor;
      body.style.backgroundColor = "#" + RandomColor;
    }
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step:2

Then we need to add code for style.css which code i provide in below screen.

* {
  padding: 0;
  margin: 0;
  font-family: 'IBM Plex Sans', sans-serif;
} 
body {
    height: 100vh;
}
.flex-row-outer {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}
.colorBtn {
    background-color: #0f62fe;
    border: 1px solid transparent;
    color: #fff;
    cursor: pointer;
    font-size: 18px;
    width: 100%;
    text-align: left;
    outline: none;
    line-height: 25px;
    padding: calc(.875rem - 3px) 60px calc(.875rem - 3px) 20px;
}
span#hexCode {
    color: #fff;
    display: block;
    padding: calc(.875rem - 3px) 60px calc(.875rem - 3px) 20px;
}
Enter fullscreen mode Exit fullscreen mode

Random Hex Color Code Output:

For more interesting content

Visit for more!

Discussion (0)

pic
Editor guide