Tutorials

Learn web design and programming with our free video and text tutorials.

Web Designer? Design and market your own professional website with easy-to-use tools.

How To Insert Images into Web Pages

This tutorial shows you how to insert an image into your web page with (X)HTML.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>
</head>
<body>

<p>
<img src="image.jpg" width="80px" height="80px" alt="some text" />
</p>

</body>
</html>

The code above produces the image below.

some text

The img tag is used to insert an image in a web page in (X)HTML.

The src attribute tells the browser where the image file is located. Similar to the <a>, the url can be absolute or relative. Usually, the file is relative. For example, if you have an image that is saved as "someimage.jpg" in a directory called "myimages", the image link code would be <img src="myimages/someimage.jpg" width="#" height="#" alt="some text" />.

The width and height attributes are necessary for 2 reasons:

First, most browsers, if not all, will either display the image in its original size or guess what the width and height are, which you may not want. For example, if you have an image with a width of 500 pixels and a height of 400 pixels, but you want the image appear as having a width of 250 pixels and height of 200 pixels, most browsers will display the image with the original width and height or 500px by 400px. Also, not specifying the width and height can lead to the web page downloading slower than if they were specified.

Second, it is necessary to include the alt tag in order for the code to be W3C XHTML standards compliant.

Something else to consider is that although you need to specify the width and height of an image in the (X)HTML image code itself, I highly that you use cascading style sheets (CSS) to specify the dimensions of an image, especially if the image will be displayed more than once.

The alt attribue stands for alternative description. The text in the alt attribute is displayed when an image cannot be viewed by the users. The alt attribute in the <img> tag is also necessary for the web page that the image is on to be W3C XHTML standards compliant.

Another thing to know about the <img> tag is that is a self-enclosing tag. This requires that there be a blank space followed by a forward slash (/) before the closing greater than bracket (>).