Working with Images
Images are placed using the
Specifying an Image
img tag requires a
src attribute, which tells the browser where to find the image to be placed.
Given a folder structure like:
webroot/ index.html about/ index.html css/ main.css images/ background.gif logo.png photo.jpg
There are different approaches to specifying an image location:
webroot/index.html, a relative path could be used like so:
webroot/about/index.html, the same image would be:
.. means to go up a directory, and can be used repeatedly:
../.. would go up two directories.
Absolute URLs start with a
/, so if we imagine that our
webroot directory was stored on a server such that the
webroot/index.html file is accessible at
http://example.com/index.html, then placing the logo image could be done from any html page with:
The benefit here is that this same
src path works on any html page, no matter what its location, so the same
img tag can be used on both the
webroot/index.html page and the
The downside is that the path only works if the project is stored to a proper location for serving.
Full URLs can also be used, such as:
Note: For linking to images, make sure that you have permission to use the image in this way. Even then, it is often better to host a copy of the same image, rather than link to another server, because it reduces dependency.
Accessibility and SEO
To make our images more accessible, we should always strive to include an
alt attribute as well, a piece of text to be used in lieu of the image when the image is unavailable for some reason, such as
- There was a connection error, the browser didn’t download the image.
- The file was not found, perhaps because the image got moved elsewhere and the page wasn’t updated yet to reflect the change.
- The user is running a text-based browser such as an older phone with a WAP-style browser, or a non-graphical browser like lynx.
- The user is using a screen reader because she has low vision, which will read the
alttext aloud or present it through a braille reader.
alt attributes has the added benefit of giving search engines more linguistic context about the image as it is used on your page.
Here’s what they look like:
<img src="puppy.jpg" alt="My cute puppy">
There are also three main image file formats:
- gif – can have basic transparency, typically a
pngis used instead.
- jpeg – no transparency, can be stored at different compression levels with varying amounts of “lossy-ness”, typically the best format for photos. (Try to balance between photo quality and file size.) These can use either the
.jpgextension. It is generally advisable to pick one and stick with it. I generally use
- png – supports transparency and semi-transparency, great for logos, icons, and repeating background tiles. Almost always preferable to a
gif, unless semi-transparency is not needed, and the
gifformat is significantly smaller.