Learn crucial techniques for optimizing HTML images, including the img tag and alt text, to improve search engine rankings and website accessibility.
Images are a powerful tool for enhancing web content, breaking up text, conveying information visually, and making a
page more engaging. HTML provides the <img> tag for embedding images, along with attributes that
control their display, accessibility, and SEO.
The Tag: Embedding Images
The fundamental element for including images in an HTML document is the <img> tag. It is a
self-closing (or void) tag, meaning it doesn't require a closing tag.
-
src(Source): This is a mandatory attribute that specifies the path or URL to the image file. It can be a relative path (e.g.,images/logo.png) or an absolute URL (e.g.,https://www.example.com/images/photo.jpg). -
alt(Alternative Text): This is another mandatory attribute and is crucial for accessibility and SEO. Thealttext provides a textual description of the image.-
For Screen Readers: Users who are blind or visually impaired often use screen readers that read out the
alttext, allowing them to understand the image's content. -
For SEO: Search engines use
alttext to understand the image's context and relevance, which can improve the page's search ranking. -
When Images Don't Load: If the image fails to load (due to a broken link, slow connection, or user settings), the
alttext will be displayed in its place.
-
Example:
<img src="images/dog.jpg" alt="A golden retriever playing fetch in a park">
Controlling Image Size with and
While CSS is the preferred method for controlling image dimensions, HTML provides width and
height attributes for basic sizing.
-
width: Specifies the width of the image in pixels or as a percentage. -
height: Specifies the height of the image in pixels or as a percentage.
Important Considerations:
-
Aspect Ratio: Setting only one dimension (width or height) will usually cause the browser to maintain the image's original aspect ratio. If both are set incorrectly, the image can appear distorted.
-
Layout Shift: Specifying dimensions upfront allows the browser to reserve space for the image before it loads, reducing layout shifts and improving perceived performance (Cumulative Layout Shift - CLS).
-
CSS Overrides: CSS styles will override the
widthandheightattributes if they conflict. It's generally recommended to use CSS for responsive image sizing.
Example:
<img src="images/logo.png" alt="Company Logo" width="150" height="50">
Responsive Images: Adapting to Different Screens
For modern web design, serving appropriately sized images based on the user's device and screen size is essential.
HTML5 provides <picture> element and srcset attribute for this purpose.
The Element:
The <picture> element acts as a wrapper for multiple <source> elements and a
single <img> element. It allows you to define different image sources for different conditions
(e.g., screen size, resolution, or image format).
-
<source>: Specifies different media or image sources.-
media: Defines a media condition (like a media query, e.g.,(min-width: 1024px)). The browser selects the first<source>that matches the media condition. -
srcset: Provides a list of image URLs and their descriptors (like width descriptorswor pixel density descriptorsx). -
type: Specifies the MIME type of the image (e.g.,image/webp,image/png).
-
-
<img>: The fallback image. This is always required and will be displayed if none of the<source>elements match or if the browser doesn't support the<picture>element.
Example:
<picture>
<source srcset="images/large-flower.webp" type="image/webp" media="(min-width: 1200px)">
<source srcset="images/medium-flower.webp" type="image/webp" media="(min-width: 800px)">
<img src="images/small-flower.jpg" alt="A blooming flower">
</picture>
This example serves different WebP images for larger screens and falls back to a JPG for smaller screens.
The and Attributes on :
You can also use srcset and sizes directly on the <img> tag for
responsive images, which is simpler than the <picture> element when you don't need different
image formats or art direction.
-
srcset: A comma-separated list of image URLs along with their width descriptors (w) or pixel density descriptors (x).-
Width descriptors (
100w,200w, etc.) indicate the intrinsic width of the image file. -
Pixel density descriptors (
1x,2x, etc.) indicate the display density the image is intended for.
-
-
sizes: Tells the browser information about the image's display size at different viewport widths. This helps the browser choose the most appropriate image fromsrcset.
Example:
<img src="images/default-flower.jpg"
srcset="images/flower-480w.jpg 480w,
images/flower-800w.jpg 800w,
images/flower-1200w.jpg 1200w"
sizes="(max-width: 600px) 480px,
(max-width: 1000px) 800px,
1200px"
alt="A beautiful flower">
In this example, the browser uses the sizes attribute to determine the current display width and then
selects the best-matching image from srcset based on its width descriptor.
Image Formats
Different image formats have different use cases:
-
JPEG (.jpg, .jpeg): Best for photographs and images with complex colors and gradients. It uses lossy compression, meaning some data is lost, resulting in smaller file sizes but potentially lower quality if compressed too much.
-
PNG (.png): Ideal for graphics with sharp lines, text, logos, and images requiring transparency. It uses lossless compression, preserving image quality but often resulting in larger file sizes than JPEG.
-
GIF (.gif): Supports animation and transparency but is limited to 256 colors. Best for simple animations and graphics where color depth is not critical.
-
SVG (.svg): Scalable Vector Graphics. An XML-based format for describing two-dimensional graphics. SVGs are resolution-independent, meaning they can scale to any size without losing quality. Excellent for logos, icons, and illustrations.
-
WebP (.webp): A modern image format developed by Google that offers both lossy and lossless compression, as well as transparency and animation. It generally provides smaller file sizes than JPEG and PNG at comparable quality. Browser support is now widespread.
Best Practices for Images:
-
Use Descriptive
altText: Make it informative for accessibility and SEO. -
Choose the Right Format: Use JPEG for photos, PNG for graphics with transparency, SVG for logos/icons, and WebP for general web use due to its excellent compression.
-
Optimize Images: Compress images to reduce file size without significant quality loss. Tools like TinyPNG or image optimization plugins can help.
-
Implement Responsive Images: Use
<picture>,srcset, andsizesto serve appropriate image versions for different devices and screen sizes. -
Specify Dimensions: Use
widthandheightattributes or CSS to help browsers reserve space and prevent layout shifts. -
Consider Lazy Loading: For pages with many images, implement lazy loading so images are only loaded when they are about to enter the viewport, improving initial page load time. This can be done with the
loading="lazy"attribute on<img>and<iframe>tags.
By following these guidelines, you can effectively incorporate images into your web pages, making them visually appealing, accessible, and performant.
Related Articles
Our most attended masterclasses
Comments
Our most attended masterclasses