CS 100 (Learn) — CS 100 (Web) — Module 07
To insert an image (picture) into an HTML document, use the <img>
tag.
<img src="goose.jpg">
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.
<img src="https://www.student.cs.uwaterloo.ca/~cs100/uwcrest.png">
The width
attribute specifies the width of the image (in pixels).
<img src="goose.jpg" width="50">
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:
<img src="goose.jpg" height="30" width="150">
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.
<img src="goose.jpg" width="25%">
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.
<img src="goose.jpg" alt="The Majestic Canadian Goose">
Once source of frustration for HTML beginners is how images are displayed inline with text.
This is a goose image:
<img src="goose.jpg" alt="The Majestic Canadian Goose">
with some following text.
This is a goose image:
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".
<a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">
<img src="goose.jpg" alt="The Majestic Canadian Goose">
</a>