HTML Images

Images, such as photos or graphics, enhance the visual appeal of a web page. Images are defined with the <img> tag. It is empty tag, contains attributes only, and does not have a closing tag.

images/articles/html/html-image-tag.webp

1. Syntax and Example

The image (img) tag allows you to grab an image file and incorporate it into the page directly.

<img src="/my_image.jpg" alt="Alternate Text" style="width:128px;height:128px" />

2. Image Attributes

  1. The src attribute defines the URL (web address) of the image. This can be an absolute or relative.
  2. The alt attribute specifies an alternate text for the image. Alternate text information is used when the user has images turned off and by screen readers. For SEO purpose and screen readers, always use appropriate alt attribute.
  3. The style attribute is used to style the image like specifying the width and height of an image. Always specify the size of an image. If the size is unknown, the page will flicker while it loads.

In a web page, small images are often shown at about 320 x 240 pixels, and larger images are often 640 x 480 pixels.

3. Figure Caption

The <figure> element is used in conjunction with the <figcaption> element to mark up diagrams, illustrations, photos, images and other things.

The <figcaption> element is optional and can appear before or after the content within the <figure>.

<figure>
<img src="/my_image.jpg" alt="Alternate Text" />
 <figcaption>
   <p>This is an image of something.</p>
 </figcaption>
</figure>

You can now semantically associate captions with their image counterparts.

4. Image Formats

The GIF is best used when you need transparency or animation. Avoid using GIF on photos, as you won't get optimal compression, and you may lose color data.

The JPG format (sometimes also called JPEG) is a relatively old format designed by the Joint Photographic Experts Group. It is most useful for photographic images, which are best suited for the JPG compression technique. However, JPG isn't suitable for images that require transparency. Text in JPG images tends to become difficult to read because of the lossy compression technique.

The PNG (Portable Network Graphics) is useful in most situations. Like GIF, PNG stores data without losing any information. It supports as many colors as you want. You are not limited to 256 colors like you are in GIF.

The WEBP is a modern image format that provides superior lossless and lossy compression for images on the web. Using WebP, you can create smaller, richer images that make the web faster.