The background in HTML is a visual layer that can enhance the appearance of a web page. You can set the background for an entire page or specific elements using CSS. The background can consist of:
- Colors: Solid colors like
blue
,red
, or hex codes like#ffffff
for white. - Images: Adding an image as a background.
- Gradients: Linear or radial gradients for a stylish look.
- Patterns: Repeated small images for a tiled effect.
1) HTML and CSS for Backgrounds
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Background Example</title>
<style>
/* Page Background */
body {
margin: 0;
padding: 0;
background-color: #f0f8ff; /* Light blue background color */
background-image: url(‘background.jpg’); /* Replace with your image path */
background-size: cover; /* Ensures the image covers the entire viewport */
background-repeat: no-repeat; /* Prevents the image from repeating */
background-attachment: fixed; /* Background image stays fixed during scrolling */
}
/* Section with Gradient Background */
.gradient-section {
height: 200px;
display: flex;
justify-content: center;
align-items: center;
color: white;
font-size: 24px;
background: linear-gradient(to right, #ff7e5f, #feb47b); /* Gradient background */
}
/* Box with Pattern Background */
.pattern-box {
width: 300px;
height: 200px;
margin: 20px auto;
padding: 10px;
color: white;
text-align: center;
background-image: url(‘pattern.png’); /* Replace with your pattern image */
background-repeat: repeat; /* Repeats the image to create a pattern */
border: 2px solid #fff;
border-radius: 10px;
}
/* Transparent Box with Background Overlay */
.overlay-box {
width: 80%;
margin: 20px auto;
padding: 20px;
background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black */
color: white;
text-align: center;
border-radius: 10px;
}
</style>
</head>
<body>
<!– Gradient Section –>
<div class=”gradient-section”>
Stylish Gradient Background
</div>
<!– Pattern Box –>
<div class=”pattern-box”>
This is a box with a repeated pattern background.
</div>
<!– Transparent Box –>
<div class=”overlay-box”>
This text is displayed over a semi-transparent background overlay.
</div>
</body>
</html>