SmartCodingTips

Using Images in HTML

Images are an essential part of web pages, used to add visual content and improve user engagement. The HTML <img> tag allows you to embed images easily.

Basic Image Tag

The <img> tag is self-closing and requires the src attribute to specify the image source URL, and the alt attribute for alternative text.


<img src="images/photo.jpg" alt="A beautiful scenery">
            

The alt attribute is important for accessibility and SEO as it describes the image when it cannot be displayed or read by screen readers.

Common Attributes

  • src: Path or URL to the image file.
  • alt: Alternative text describing the image.
  • width and height: Specify image dimensions in pixels.
  • title: Text shown as tooltip on hover.

Example with Attributes


<img src="images/logo.png" alt="Company Logo" width="200" height="100" title="Our Logo">
            

Responsive Images

To make images responsive and adapt to different screen sizes, use CSS such as:


img {
    max-width: 100%;
    height: auto;
}
            

This ensures images scale down properly without distortion.

Using Images from External Sources

You can also link to images hosted on other websites by using an absolute URL in the src attribute:


<img src="https://example.com/images/sample.jpg" alt="Sample Image">
            

Be cautious with external images to ensure they are reliable and fast-loading.

Image Formats

  • JPEG/JPG: Best for photos, supports millions of colors with lossy compression.
  • PNG: Supports transparency, good for logos and graphics with sharp edges.
  • GIF: Supports animation but limited to 256 colors.
  • SVG: Scalable vector graphics, great for icons and logos without quality loss.
  • WebP: Modern format with better compression and quality, supported in most browsers.

Best Practices

  • Always provide meaningful alt text for accessibility.
  • Optimize images for web to reduce file size and improve load times.
  • Use responsive techniques for mobile-friendly layouts.
  • Use modern formats like WebP when possible for better performance.