HTML Image Tag – Adding and Optimizing Images

Images make web pages more engaging and informative. Whether it is a logo, banner, or illustration, you will use images a lot in web design.

In this tutorial, you will learn:

  • How to insert an image using <img> tag
  • What each attribute means
  • How to style images using basic HTML/CSS

HTML Image Tag

Here’s the basic syntax to add an image:

<img src="image.jpg" alt="A description of the image" title="title of the image"/>

Explanation:

  • <img/> – it’s an open tag, means it does not has any range
  • src – specifies the path or URL to the image file
  • alt – this attribute holds the text to be shown if image fails to load (also important for SEO and accessibility)
  • title – It is optional and offers supplementary information. we see this text when hovering over the image.

Using Online Images

You can also use images from the web: to do this you need to use absolute URL in src value.

Example:

<img src="https://example.com/image.jpg" alt="Example image">

Be sure you have permission to use external images. Some time you need to give attribution in the manner specified by the author or licensor. Don’t ever use copyrighted images.

Setting Width and Height

You can define dimensions directly in the tag:

Example:

<img src="logo.png" alt="Site Logo" width="200" height="100">

Note that using CSS is better for responsive design.

Styling Images with CSS

Here’s a simple way to style your image:

Example (HTML part):

<img src="banner.jpg" alt="Banner" class="hero">

Example (CSS part):

.hero {
  width: 100%;
  height: auto;
  border-radius: 10px;
}

Explanation:

  • For styling you can target img element directly, but it will style all images in the document.
  • To target one particular image we have assigned a class="hero" in the above example.
  • width: 100%; – by this property image will stretch to fill the width of its container

Best practice for responsive images

.hero {
  width: 100%;
  max-width: 600px;
  height: auto;
  border-radius: 10px;
}

Why? because:

  • Image scales with the container width
  • But never gets wider than 600px
  • Always keeps aspect ratio

Image Formats to Use

  • .jpg or .jpeg – Great for photographs
  • .png – Supports transparency
  • .svg – Scalable vector graphics, good for icons/logos
  • .webp – Modern format with better compression

Summary

AttributePurpose
srcPath to the image
altDescription text for SEO & fallback
titleoffers supplementary information (Optional)
width/heightSets image size
classAdds CSS class for styling

Practice Challenge

Create an HTML page and:

  • Insert an image from your local folder
  • Add an online image
  • Apply a class to round its corners with CSS
  • Add appropriate alt text to both

Sharing Is Caring...