They say an image is worth a thousand words and that goes for HTML images too. Images help to enrichen your web pages. You can add images to any web page using the <img>
tag in the following syntax.
<img src="Image URL or encoded data" [other optional attributes]>
Unlike other tags we have seen so far, the <img>
tag is an empty tag, which means that it can contain only a list of attributes and it has no closing tag.
Example:
<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
</head>
<body>
<p>Image inserted</p>
<img src="logo.png" alt="Brightwhiz.com logo">
</body>
</html>
The src Attribute
The tag loads the image resource from the value specified in the src attribute. Images are usually stored on the web server or somewhere on the Internet in a separate folder. By specifying the path and file name the web browser will navigate to the location and load the image where the tag is positioned in the HTML document.
Usually, image formats that you can load are those supported by the web browser. If the image is not supported the browser will download it as though it was any other binary file such as a ZIP file.
Common Image Formats
Abbreviation | File Format | File Extension |
APNG | Animated Portable Network Graphics | .apng |
GIF | Graphics Interchange Format | .gif |
ICO | Microsoft Icon | .ico, .cur |
JPEG | Joint Photographic Expert Group image | .jpg, .jpeg, .jfif, .pjpeg, .pjp |
PNG | Portable Network Graphics | .png |
SVG | Scalable Vector Graphics | .svg |
WebP | open format for lossy compressed true-color graphics | .webp |
The alt Attribute
The required alt attribute provides an alternate text for an image. This text is displayed instead of the image in the event that the user cannot load the images due to various reasons such as slow connection, a missing image at the specified source, or if the user is using a screen reader.
Typically, the alt attribute value should be something descriptive of the image.
Image Size – Width and Height
You can use the width and height attributes to specify the display size in pixels.
Example:
<img src="logo.png" alt="Brightwhiz.com logo" width="480" height="270">
You can also use the style attribute to specify the image size. Using the style attribute is not restricted to pixels. Using style also prevents any CSS stylesheets from modifying the image size seeing CSS styles supersede the width and height attribute.
Example:
<img src="logo.png" alt="Brightwhiz.com logo" style="width:480px;height:270px;">
Note: Always specify the width and height of an image. That way you preserve the page layout and if for any reason the image doesn’t load you still keep the layout. Specifying the image size also improves the web page rendering performance.