HTML First Steps - Lesson 6 - Images
Images are a very important element of a website—without them, it looks dull and unattractive. Images are used for visual design, photo galleries, or just to enhance content.
Images are inserted using the IMG tag (note that we write img, not the full word “image”). The IMG tag is self-closing: <img />, meaning it doesn’t require a closing tag.
The most important attribute of the IMG tag is src. It works like href in a link—we must specify the image path in src. The path can be relative or absolute.
Here is the code of our index.html file:
<html>
<head>
<title>My First HTML Document</title>
</head>
<body>
<h1>My First HTML Document</h1>
<p>
<a href="files/file.html">Link to second document</a>
</p>
</body>
</html>
Now let’s create a folder named images next to this file. In the images folder, place the image file—let’s say it’s named image.jpg. Let’s add the img tag into index.html.
<html>
<head>
<title>My First HTML Document</title>
</head>
<body>
<h1>My First HTML Document</h1>
<p>
<img />
</p>
<p>
<a href="files/file.html">Link to second document</a>
</p>
</body>
</html>
Now let’s write the relative path to the image, starting with ./
./
Then we add the folder name:
./images/
And then the file name:
./images/image.jpg
Insert this path into the src attribute of the image tag:
<html>
<head>
<title>My First HTML Document</title>
</head>
<body>
<h1>My First HTML Document</h1>
<p>
<img src="./images/image.jpg" />
</p>
<p>
<a href="files/file.html">Link to second document</a>
</p>
</body>
</html>
By default, the image displays at its original size, but we can change that using width and height attributes.
Use width for the image width and height for the height. You can use either or both attributes. For example:
Only width:
<img src="./images/image.jpg" width="200" />
Only height:
<img src="./images/image.jpg" height="400" />
Both height and width:
<img src="./images/image.jpg" height="400" width="100" />
If you specify both, make sure the ratio matches the original image dimensions, otherwise the image will look distorted.