CS 100 (Learn)CS 100 (Web)Module 07


HTML :: Images

To insert an image (picture) into an HTML document, use the <img> tag.

HTML
<img src="goose.jpg">
web browser

 

The src attribute is the filename.

Just like with hyperlinks (<a href="...">), the file can be in the same folder (so you can just specify the file, as above) or it could be a full web address.

HTML
<img src="https://www.student.cs.uwaterloo.ca/~cs100/uwcrest.png">
web browser

 

The width attribute specifies the width of the image (in pixels).

HTML
<img src="goose.jpg" width="50">
web browser

 

If you do not specify a width attribute, it will display the image at its native (or full) size. You can also specify the height attribute, but it is best to avoid specifying both width and height, as it may accidentally distort the image:

HTML
<img src="goose.jpg" height="30" width="150">
web browser

 

Instead of specifying the width as a number of pixels, you can add a percentage to the width attribute and it will be a percentage of the screen width. If you resize your browser, the width should adjust accordingly. This may or may not be desirable in your application.

HTML
<img src="goose.jpg" width="25%">
web browser

 

You should also always add an alt attribute to specify a description of the image for the visually impaired or for environments where images cannot be displayed.

HTML
<img src="goose.jpg" alt="The Majestic Canadian Goose">
web browser

The Majestic Canadian Goose

 

Once source of frustration for HTML beginners is how images are displayed inline with text.

HTML
This is a goose image:
<img src="goose.jpg" alt="The Majestic Canadian Goose">
with some following text.
web browser

This is a goose image: The Majestic Canadian Goose with some following text.

 

You can use paragraphs (<p>) or possibly line breaks (<br>) to fix this problem. In the following module we will see that there are better alternatives (using style).

Finally, a common practice is to combine links with images to make an image a link. Remember, that everything between the <a> and </a> are "clickable".

HTML
<a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">
  <img src="goose.jpg" alt="The Majestic Canadian Goose">
</a>
web browser

The Majestic Canadian Goose