Images and Figures

We can embed an image in a web page using the inline img element and its src attribute.  The src attribute is set to the location of the image file with an absolute path or a relative path.  Below are two examples.  The first displays the CSS3 logo that is stored on the host machine.  The second displays the HTML5 logo using a URL to a resource on another server.

Notice the img element doesn’t include a closing tag.  The image element is an empty element, that is, they cannot contain content.  Therefore it is often an error to include a closing tag.

<img src="images/css3.png" width="64">
<img src="https://upload.wikimedia.org/wikipedia/commons/6/61/HTML5_logo_and_wordmark.svg" width="64">

The height and width Attributes

As shown above, the width attributes can be used to resize the images, different from their original sizes, however it is recommended to avoid using the width and height attributes and use an image editor to resize an image to the size that you want displayed.

The alt Attribute

The alt attribute can be set alternative text which is displayed when the image cannot be displayed.

<img src="images/nonexistent_file.png" alt="CSS 3 Logo">

CSS 3 Logo

The title Attribute

The title attribute can provide text that is displayed as a tooltip when the user hovers the cursor over the image.

<img title="CSS 3 Logo" src="images/css3.png">


Attribution

The Mozilla documentation on embedding images has an important warning about using images created by others.  I’ve copied it below.

Warning: Most images are copyrighted. Do not display an image on your webpage unless:1) you own the image
2) you have received explicit, written permission from the image’s owner, or
3) you have ample proof that the image is, in fact, in the public domain.Copyright violations are illegal and unethical. In addition, never point your src attribute at an image hosted on someone else’s website that you don’t have permission to link to. This is called “hotlinking”. Again, stealing someone’s bandwidth is illegal. It also slows down your page, leaving you with no control over whether the image is removed or replaced with something embarrassing.

figure and figcaption elements

HTML5 provides a semantic block element named figure that can contain img elements and figcaption elements.  The figcaption element is used to hold text that is displayed with the image.  The text can be used to provide a title, description, or attribution.

<figure>
    <img title="CSS 3 Logo" src="images/css3.png">
    <figcaption>By Rudloff [CC BY 3.0 (http://creativecommons.org/licenses/by/3.0)], via Wikimedia Commons</figcaption>
</figure>
By Rudloff [CC BY 3.0 (http://creativecommons.org/licenses/by/3.0)], via Wikimedia Commons

© 2018 – 2020, Eric. All rights reserved.