Certainly! Below is an example of a simple HTML page with a button that, when clicked, changes the background color to a random pastel color. In this code, JavaScript is used to generate a random pastel color by altering the RGB values.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Pastel Color Background</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
transition: background-color 0.5s; /* Smooth transition for color change */
}
.color-changer-btn {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<button class="color-changer-btn" id="colorChanger">Change Background Color</button>
<script>
function getRandomPastelColor() {
// Generate random light colors (pastels)
const base = 256;
const offset = 127; // Adjust this to make colors lighter or darker
const r = Math.floor(Math.random() * base) / 2 + offset;
const g = Math.floor(Math.random() * base) / 2 + offset;
const b = Math.floor(Math.random() * base) / 2 + offset;
return `rgb(${r}, ${g}, ${b})`;
}
const button = document.getElementById('colorChanger');
button.addEventListener('click', function() {
document.body.style.backgroundColor = getRandomPastelColor();
});
</script>
</body>
</html>
Here's how the code works:
The CSS styles the body of the HTML to be a full vertical height and centers the button.
The transition property in the body's style provides a smooth color transition effect.
The JavaScript function getRandomPastelColor() generates a pastel color by mixing RGB with high values (for lightness) and some randomness.
The button with id colorChanger listens for a click event and changes the body's background color using the generated pastel color.
You can copy this code into an HTML file and open it in a web browser to see the effect.