CSS background-image Property with URL Value
To display an image as background, set CSS background-image property with URL value.
The syntax to specify URL value for background-image property is
background-image: url("path/to/image");
If the size of background image and HTML element are not same, the background image is not resized to that of the HTML Element.
If length or width of background image is greater than that of HTML Element, then the background image appears cropped. The top-left corner of the image and the top-left corner of the HTML Element are aligned.
If length or width of background image is less than that of HTML Element, then the background image is repeated along that axis.
We can specify multiple background images by specifying multiple url()
values, separated by comma, for background-image.
Examples
In the following examples, we try out background-image with different kinds of values for url().
background-image: url(“path/to/image”);
In the following example, we display a background-image for a div.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div {
height: 200px;
width: 400px;
line-height: 200px;
text-align: center;
font-size: 50px;
color: white;
}
#div1 {
background-image: url('https://www.tutorialkart.com/sample_image.jpg');
}
</style>
</head>
<body>
<div id="div1">Hello World</div>
</body>
</html>
background-image: url(“path/to/image”), url(“another/image”);
In the following example, we display a background-image for a div.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div {
height: 200px;
width: 400px;
line-height: 200px;
text-align: center;
font-size: 50px;
color: white;
}
#div1 {
background-image: url('https://www.tutorialkart.com/sample_image_small.jpg'),
url('https://www.tutorialkart.com/sample_image.jpg');
background-repeat: no-repeat repeat;
}
</style>
</head>
<body>
<div id="div1">Hello World</div>
</body>
</html>
background-image: url(“relative/path”);
In the following example, we give a relative path to url().
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div {
height: 200px;
width: 400px;
line-height: 200px;
text-align: center;
font-size: 50px;
color: white;
}
#div1 {
background-image: url('/sample_image_small.jpg');
}
</style>
</head>
<body>
<div id="div1">Hello World</div>
</body>
</html>
Conclusion
In this CSS Tutorial, we learned different scenarios to work with url() and background-image property, with examples.