Screen Printing

TUTORIALS » HTML / JavaScript » HTML essentials (guided tutorials)

Images in HTML



Can you imagine a web page without pictures or graphics at all? That would be boring! In this tutorial we will learn how to insert images in our HTML page and make it look great.

Web browsers allow three types of image files: JPG, PNG, and GIF. To insert an image in a HTML document you must use the
<img>
tag using the src attribute (from source) to point the path and name of the file, like:
<img src="mypicture.jpg" />
Note that since the
<img>
tag stands alone, it must be self-closed.
  1. Copy an image file to your working folder and rename it as firstimage.jpg.
  2. Create a new .html file in the same folder and write in it:
    <h1>My First Image</h1>
    
    <img src="firstimage.jpg" />
  3. Test your new .html file.
That was easy!
Note: If the image file is located in a different folder, you can use relative or absolute paths in the src path.

Image dimensions (width and height)

You can change the dimensions of the displayed image using the width and height attributes. This will not modify the actual image file, only the way it is showed on screen. The dimensions can be given in pixels or as a percentage of its container.

It is not recommended to change the actual dimensions of an image, since it will look distorted and "pixilated" (and that's ugly!). On the other hand, seting the dimensions of an image to its actual size is a good way of preventing the image from deformating due to per-user browser settings.
Play with the width and height attributes of your
<img>
tag. You could try:
<img src="firstimage.jpg" width="800" height="200" />
   or
<img src="firstimage.jpg" width="200" height="800" />
   or
<img src="firstimage.jpg" width="100%" height="50%" />
   or
<img src="firstimage.jpg" width="75%" height="300" />

The alt attribute

The alt attribute is used to write a short description of the displayed image. It helps some browsers and search engines to index the contents of a web page.

The code:
<img src="ebodius.png" width="280" height="90" alt="ebodius' logo" />
Will render something like:
ebodius' logo


If, for some reason, the browser cannot find the image file, it will still render something like:
ebodius' logo

Thanks to the
<alt>
tag we can see, at least, that there is supposed to be an image with a logo.

Images as links

You can also use images as links (instead of using only text). The syntax is the same as with text links, using the
<a>
tag:

The code:
<a href="http://www.ebodius.com/" target="_blank">

<img src="ebodius.png" width="280" height="90" alt="ebodius' logo" />
</a>
Will render something like: (Click on the image)

Well, now you know all the basics you need to add images to your web pages. Remember, you need to practice a lot if you want to become a real pro.


Are you ready for the next tutorial? Go to Lists in HTML.


More recommended tutorials:

Comments & Questions