Image Tag
Unlike most elements, the image tag is a specific reference in your HTML document to an image on your website. It is more like an advanced link to an image file. The HTML image tag actually retrieves the image and displays it in your web page. However, unlike most elements, the image tag requires an attribute in order to display an image. The opening and closing tags are a unique case in the sense that they are combined, <img />
. The primary attribute of the <img>
tag is src=""
, where you would put the link to the image in between the quotation marks. Of course, the image tag has many other attributes, but this is the most important one you need to know to get started.
Show an Image
Example
<img src="/images/smiley2.jpg" width="200"/>
Result
Pretty cool, huh? Now, you might be wondering what is this width="200"
. The width and height are both attributes of the HTML image tag. I try to only use one or the other as this permits the browser to resize the image correctly. If you used them both at the same time and they are not the proper dimensions, it will stretch or shrink the image. The src
is the attribute we set to the link to our image, /images/smiley2.jpg
.
Important Alt Attribute
The second most important attribute for an image is called the alt
attribute. The alt
attribute is only activated when an image fails to load. If you ever remove or lose an image from your website, the alt
attribute will step up and display its value to the browser. Additionally, search engines cannot read what an image is all about, so search engines use the HTML image alt
attribute to “understand” it. In conclusion, always set the alt
attribute and set it to a value that tells the user about the image.
Example
<img src="/images/smiley2.jpg" alt="A smiley face I created" width="200"/>