Using images

Adding images to your website makes for rich, engaging experiences, but adds additional load to the page. In this class we'll learn the dos and don'ts and how to work with images the right way.

HTML

Src

The most basic way to use an image is an img tag with src attribute.

<img src="image.jpg" />

The path to the image is relative to the html page, if it's in an images directory, you need to use the correct path.

<img src="images/image.jpg" />

Use a slash in front for a path relative to the site root.

<img src="/images/image.jpg" />

You can use an absolute path, but this is discouraged as the images should be hosted on your own domain.

Avoid "hotlinking" images to another domain, which can break if the image changes, or violate copyright and content policies.

<img src="https://placekitten.com/300/200" />

In this case, placekitten.com provides images for testing, which is great for development but not to be used in production!

Height/Width

Browsers don't know the image's size until it's loaded, which can cause the layout to shift.

Set height and width attributes (without px) to declare the image's size.

<img src="https://placekitten.com/300/200" width="300" height="200" />

Alt

Alt text is loaded when an image is missing, or read by screen readers.

<img src="images/image.jpg" alt="Look at my kitten!" />

Look at my kitten!

Title

Display a label when hovering over the image.

<img src="images/image.jpg" title="Look at my kitten!" />

CSS

Auto scaling

When an image is too big, you want to shrink it down to fit the container.

This CSS is typically used to contain images without skewing.

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

object-fit

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

Image file types

JPG - Most commonly encountered format, good for most images.

PNG - Higher quality format for large photos and transparent graphics.

GIF - Animated images.

SVG - Vector images, can scale to any size.

AVIF, WebP - Newer image formats for bandwidth optimzation.

Level
Topics