HTML Images
Images are an important part of web content and can greatly enhance page appeal and information delivery. HTML uses the <img> tag to embed images on a page.
<img> is an empty element; it only contains attributes and has no closing tag.
The src Attribute - Specifying Image Source
The src (source) attribute is the most important attribute of the <img> tag, specifying the path or URL of the image to display.
<img src="image_url">- Relative path: Points to an image within the website.html
<img src="images/my-cat.jpg"> - Absolute path: A complete URL pointing to an image on another website.html
<img src="https://www.example.com/images/logo.png">
The alt Attribute - Providing Alternative Text
The alt (alternative text) attribute provides alternative text for images. It serves two crucial purposes:
- Accessibility: Screen readers will read the
alttext aloud, helping visually impaired users understand the image content. - Error handling: If an image cannot be loaded for any reason (e.g., incorrect path, network interruption), the browser will display the text in the
altattribute.
A well-written alt attribute for an <img> tag is essential.
<img src="programming_cat.jpg" alt="A cat wearing glasses, coding seriously">If the image fails to load, users will see the description "A cat wearing glasses, coding seriously".
The width and height Attributes - Controlling Image Dimensions
You can use the width and height attributes to specify the image's width and height (in pixels).
<img src="logo.png" alt="Website Logo" width="500" height="150">Why is specifying dimensions important?
When the browser loads a page, if the <img> tag specifies width and height, the browser will immediately reserve the appropriate space for that image. This way, even if the image hasn't fully downloaded, the overall page layout won't jump due to image loading (this is called Layout Shift), providing a better user experience.
Note: Although you can set dimensions directly with attributes, in responsive design, it's more common to use CSS to flexibly control image size (e.g., using percentage widths).
Using an Image as a Link
To turn an image into a clickable link, simply nest the <img> tag inside an <a> tag.
<a href="https://www.example.com">
<img src="logo.png" alt="Click to visit our website">
</a>Common Image Formats
- JPEG/JPG: Best for photographs. It's a lossy compression format that can significantly reduce file size while maintaining acceptable image quality.
- PNG: Best for images requiring transparent backgrounds (like icons, logos) or graphics containing text and lines. It's a lossless compression format.
- GIF: Supports animation. Suitable for simple animated expressions or icons.
- SVG: Scalable Vector Graphics. It's based on XML and doesn't lose quality no matter how much you scale it, making it ideal for logos and icons.