Lesson 5 – HTML5 Images

Web pages do not only contain simple text. They often contain graphics, images, animations, and videos.

We actually use the image <img> element to add an image to the document. The image location or source is assigned to the source (src) attribute. The source attribute actually locates assigned image and displays it on the web. You only require to put image name in the source attribute if it is located in the same directory as HTML5 document. If not, you have to add proper path in the src attribute for it to locate the image.

The following code snippet demonstrates how to add images to your HTML5 document or a website.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Images</title>
</head>
<body>
    <h1>Including Images in HTML5 Document</h1>

    <p>
        <img src="earth.jpg" alt="Earth Image">
        <img src="mars.jpg" alt="Mars Image">
    </p>
</body>
</html>

Your webpage or website will display the following images once the browser executes this code.

By default, HTML5 will display the images side by side. This is because img is an inline element. Inline elements are those elements which flow along with the text. Therefore, they do not drop to the next line by clearing the previous content.

The block-level elements, on the other hand, will expand to the width of the parent container if we don’t set any width. Similarly, the will expand to the height of parent container if no height is set.

Alt Attribute

Coming back to images, alt is one of the most important attributes of the img element. There are many reasons a browser may not be able to display an image and this is where the alt attribute can come to your rescue. For example, the browser will display the value of alt attribute if it cannot render the image due to any reason. Have a look at the following code snippet.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Images</title>
</head>
<body>
    <h1>Including Images in HTML5 Document</h1>

    <p>
        <img src="earth.jpg" alt="Earth Image" width="300" height="300">
        <img src="jupiter.jpg" alt="Mars Image" width="300" height="300">
    </p>
</body>
</html>

In this example, we have assigned the wrong path to source attribute for the Mars image. As a result, the browser will only display the alt text that is “Mars Image” rather than rendering the original image as demonstrated by the following image.

The “width” and “height” are optional attributes which you can use to set an image’s dimension without using Cascade Style Sheet (CSS).

In the next chapter, we will talk about adding audios and video files to HTML5 document.