Using Images

The <img> tag

The <img> tag is the simplest and most common way to display an image in an html page. 😊 It requires a src attribute, which indicates where the browser will find the image, and an alt attribute, which provides a textual version of the image for screen-readers.

Example: Smiley face icon

<img src="path/to/image.jpg" alt="My image">

Sizing an <img>

<img> tags can be sized with CSS. Generally, it is best to set only width or height, not both.

Cloudy day

Cropping an <img>

We can crop by forcing width/height and using object-fit: cover;

Cloudy day cropped

Background images

Shelf Cloud: A low-hanging, well-defined, wedge-shaped formation that occurs along the leading edge of a gust front in a thunderstorm. Shelf clouds most often form just ahead of intense lines of thunderstorms.

Preparing images for the web

A comparison of image file types

jpg gif png svg
jpg smiley gif smiley png smiley svg smiley
jpg shelf cloud 36KB
gif shelf cloud 138KB
png shelf cloud 422KB
Not applicable, SVG is vector only!
Pros:
  • Very small file size for photos
Pros:
  • Can be animated
  • Small file size for solid colors
Pros:
  • Lossless compression
  • Full transparency
  • Works for photos and graphics
Pros:
  • Lossless compression
  • Full transparency
  • Infinite scaling
  • Usually small file size
Cons:
  • Lossy compression
  • Adds artifacts in areas of high contrast
  • No transparency
Cons:
  • Limited color palette
  • High noise/banding
  • Larger file size
  • 1-bit transparency (rough edges)
Cons:
  • Very large file size
Cons:
  • No support for raster images

Managing file size

Compressed cloud picture
1680px wide, 50% compression, 143 KB

"Resolution" is just ratio.

Raster images are pixels, but a pixel has no fixed physical size. 300 pixels may occupy one inch in print, while a billboard pixel could be larger than an inch. When we care about data in an image, we ask for its pixel dimensions (width × height), not “72dpi.”