There are many situations when both the HTML <img> tag and CSS background-image property give the same visual outcome. But what is the difference between them? Well, in this snippet, we’re going to discuss the differences between them, after which you can make a better decision when using them.
Use the <img> tag in the following cases:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h2>Example</h2>
<img src="https://images.unsplash.com/photo-1585409677983-0f6c41ca9c3b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="Nature" width="500" height="333">
</body>
</html>
Use the CSS background-image property in the following cases:
Let’s see an example with the background-image property, where it is used with the background-size property with the “cover” value.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.image {
background-image: url("https://images.unsplash.com/photo-1433838552652-f9a46b332c40?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60");
background-color: #cccccc;
height: 500px;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
position: relative;
}
</style>
</head>
<body>
<div class="image"></div>
</body>
</html>