Background images in HTML are specified by using
- the
style
attribute - the
<style>
element - or in the
CSS files
You can specify a background image for almost every HTML element.
How to Specify
To set a background image on an HTML element, use the HTML style
attribute along with the CSS background-image
property, as shown below.
<p style="background-image: url('image.png');">This is a paragraph.</p>
You can alternatively define the background image for an HTML element by using the <style>
element within the <head>
section
<head>
<style>
p {
background-image: url('image.png');
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
</body>
Both examples above will result in the preview shown below.
Note: In the above example, we have also given width
and height
to the <p>
element to create the preview, because background images are only shown up to the maximum width and height of the HTML element.
Full Page Background Image
If you want the entire page to have a background image, you must specify the background image for the <body>
element, as shown below.
<style>
body {
background-image: url('image.png');
}
</style>
Background Repeat
By default, If the background image is smaller than the element, it will repeat horizontally and vertically until it fills the element.
To prevent the background image from repeating, set the background-repeat
property to no-repeat
.
<style>
body {
background-image: url('image.png');
background-repeat: no-repeat;
}
</style>
Full Background Cover
To ensure that the background image covers the entire element, set the background-size
property to cover
.
<style>
body {
background-image: url('image.png');
background-repeat: no-repeat;
background-size: cover;
}
</style>
Background Stretch
To stretch the background image to fit the entire element, set the background-size
property to 100% 100%
.
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-size: 100% 100%;
}
</style>
This will stretch the image to the HTML element's dimensions to cover it completely, but it causes the image distortion in most cases, as shown below.
Please check below options for the links to our previous or next tutorial.