In HTML, you can set a background image for a web page or a specific HTML element using the background-image
CSS property.
Here is an example of setting a background image for a web page:
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<style>
body {
background-image: url("background.jpg");
background-size: cover;
}
</style>
</head>
<body>
<h1>Welcome to my web page!</h1>
<p>This is some text on my web page.</p>
</body>
</html>
In this example, the background-image
property is used to specify the URL of the background image (background.jpg
), and the background-size
property is used to set the size of the image to cover the entire background of the page. The body
element is used to apply the background image to the entire page.
You can also set a background image for specific HTML elements, such as a <div>
element:
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<style>
.mydiv {
background-image: url("background.jpg");
background-size: cover;
}
</style>
</head>
<body>
<h1>Welcome to my web page!</h1>
<div class="mydiv">
<p>This is some text in a div element with a background image.</p>
</div>
</body>
</html>
In this example, the background-image
property is applied to the .mydiv
CSS class, which is then applied to the <div>
element. This sets the background image for the <div>
element only, and not for the entire web page.
It’s important to optimize background images for the web by reducing their file size and dimensions as much as possible without sacrificing image quality, as large or uncompressed images can slow down web page loading times.