Unleash Your Creativity: Build a Stunning Colour Generator with HTML, CSS, and JavaScript
Table of Contents
In this article, we will learn to create a simple and powerful colour generator using HTML, CSS, and JavaScript. This colour generator will generate random colours and display HEX and RGB codes. In this article, you will learn how to build a simple colour generator.
Before you start this project, you need to have a basic understanding of HTML, CSS, and JS. If you are a beginner and don’t have enough knowledge of the functionalities of HTML, CSS, and JS, you can refer to our Programming tab for more details.
Here are the Steps to build a Colour Generator
Step1: Write the HTML code as shown below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<h2 id="color-code"> # Color Code </h2>
<button id="btn">Click to change color</button>
</div>
<script src="index.js"></script>
</body>
</html>
Step 2: Write the CSS code as shown below.
@import url('https://fonts.googleapis.com/css2?family=Oswald:wght@200;300&family=Roboto:wght@100&display=swap');
*{
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
}
#container{
width:30%;
margin: 10px;
padding: 10px;
border-radius: 5px;
font-size: 40px;
text-align: center;
transition: 1s;
}
button{
width: 100%;
background-color: black;
display: block;
font-size: 40px;
color: white;
border: none;
border-radius: 5px;
margin-top: 5px;
}
Step 3: Write the JS code as shown below
const getColor = () => {
const randomNumber = Math.floor(Math.random() * 16777215);
const randomCode = "#" + randomNumber.toString(16);
const container = document.getElementById("container");
container.style.backgroundColor = randomCode;
document.getElementById("color-code").innerText = randomCode;
}
document.getElementById("btn").addEventListener("click", getColor);
Explanation
HTML: HTML gives a structure to our project. This project contains a div for colour codes and a button to generate random colours which works through logic as given in the Javascript file.
CSS: CSS file styles the project giving it a clean and attractive look. The div changes its background colour every time the button is clicked.
JS: JS gives logic in generating random colours with HEX and RGB codes.
Conclusion
By following these steps you can create a random colour generator using HTML, CSS and Javascript. This project will help you enhance your skills in web development.
Follow us on Facebook. If you have any query, you can comment below or message us on our facebook page.
Happy Learning!