As you saw in Lesson 5, images can be inserted into web pages very easily with the <img> element. This lesson expands a bit on how images can be controlled.
The alt attribute is used to define "alternate text" for an image. If
the browser cannot load the image for one reason or another, it will display
the alternate text. For example, the source file for the image to the right
is "images/dog_with_cats.jpg." If for some reason, the file cannot be loaded,
perhaps because the name is wrong or it is not in that folder, or we do not
have permission to open it, then the alt text "Cats" will be displayed
instead. If you have downloaded the zip file for these lessons, try renaming
that file and reloading this page to see what happens.
The value of the alt attribute is up to you.
It is required to include the "alt" attribute for each image on a page, to be
valid HTML. It also improves the display and usefulness of your document
for people who have text-only browsers.
The title attribute is an optional attribute that defines the text that will be displayed when the cursor hovers over the image for a second or two. It is used to provide extra information to the user.
In general it is bad idea to ask the browser to change the size of the image. The image, as it is stored in the image file, is a fixed size. If the size attributes are set to different values than the image's actual size, the browser will resize the image to the size that you specify, but the image will most likely be distorted, and/or the quality will be worse than the original. The actual size is not changed -- only what appears on the page. Therefore, it is best to match the size attributes of the img element to the actual size of the image file. You can find the actual size of the image in a few different ways.
The actual size of the above image is 400 by 249 pixels.
If you want to change the size of the original image file, you can do this in GIMP by cropping the image to the size that you want, or by rescaling it proportionally. You can also do this in Linux with the ImageMagick program.
The next four images are all obtained by resizing the image above. The first two distort it. The second two preserve the proportions and either reduce or enlarge it.
![]()
|
![]()
|
![]()
|
![]()
|
There are ways to resize the image and preserve the proportion. If you specify just one dimension, either the width or the height, the browser will match the other dimension to the oen you specify so that the image proportion is preserved. Image width or height can also be expressed in percentages. If you specify width=50% for example, it will take up 50% of the width of the element in which it is contained.