Sobes.tech
Junior — Middle

What are the differences between the img tag and the CSS background-image property when adding images to a page?

sobes.tech AI

Answer from AI

The <img> tag is used to insert images as standalone content on a page. It is a semantic element that the browser treats as a separate object with its own attributes (alt, width, height, etc.). An image via <img> participates in the document flow and affects its size and layout.

The CSS property background-image sets an image as the background for an element. It is a decorative element that does not affect the document structure and is not perceived as content. Background images do not have attributes like alt and are not indexed by search engines as separate images.

Main differences:

  • <img> is content, background-image is decoration.
  • <img> affects size and document flow, background does not.
  • <img> supports alternative text, background does not.
  • Background can be easily positioned, repeated, and resized using CSS.

Example:

<img src="photo.jpg" alt="Photo description" width="300" height="200">

<div style="width:300px; height:200px; background-image: url('photo.jpg'); background-size: cover;"></div>