<!DOCTYPE html>
<html>
<head>
<title>Random Red Background</title>
<style>
body {
background-color: #ccc; /* default background color */
}
button {
background-color: #fff; /* white button */
color: #333; /* black text */
padding: 10px 20px; /* button padding */
border: none; /* no border */
border-radius: 5px; /* rounded corners */
cursor: pointer; /* pointer cursor */
}
button:hover {
background-color: #ccc; /* hover background color */
}
</style>
</head>
<body>
<button onclick="changeBackground()">Click me!</button>
<script>
function changeBackground() {
// generate a random shade of red
var red = Math.floor(Math.random() * 256);
var green = 0;
var blue = 0;
var color = "rgb(" + red + ", " + green + ", " + blue + ")";
// set the background color to the random shade of red
document.body.style.background = color;
}
</script>
</body>
</html>
This code creates a basic web page with a button that, when clicked, changes the background color to a random shade of red using JavaScript.
The HTML code defines a button with a white background and black text, and adds an event listener to the button's onclick attribute that calls the changeBackground() function when the button is clicked.
The CSS code sets the default background color of the page to a light gray color (#ccc), and styles the button with a white background and black text. It also adds a hover effect to the button that changes its background color to a darker gray color (#ccc) when the mouse is hovered over it.
The JavaScript code generates a random shade of red by using the Math.floor(Math.random() * 256) method to generate a random number between 0 and 255, and then setting the red, green, and blue values of the color to that number. It then sets the background color of the page to the generated color using the document.body.style.background property.
Note that this code uses the rgb() color model to define the color, which takes three arguments: the red, green, and blue values of the color, respectively. You can adjust the range of the random number generator to get different shades of red. For example, if you want a darker shade of red, you could use Math.floor(Math.random() * 128) instead of Math.floor(Math.random() * 256).