The img
element allows you to embed an image into an HTML document.
It has local attributes:src, alt, height, width, usemap, ismap
.
The border, longdesc, name, align, hspace
, and vspace
attributes are obsolete in HTML5.
To embed an image, you need to use the src
and alt
attributes as follows.
<!DOCTYPE HTML>
<html>
<body>
<img src="http://www.java2s.com/style/download.png"
alt="Triathlon Image"
width="200"
height="67" />
</body>
</html>
The src
attribute specifies the URL for the image.
The alt
attribute defines the content if the image cannot be displayed.
The width
and height
attributes set the image size (in pixels).
A common use of the img
element is to
create an image-based hyperlink in conjunction with the a
element.
The following code shows how you can use the img
and a
elements together.
<!DOCTYPE HTML>
<html>
<body>
<p>
<a href="http://java2s.com/page.html">
<img ismap src="http://www.java2s.com/style/download.png"/>
</a><!-- ww w.j a va2 s .c o m-->
</p>
</body>
</html>
If you apply ismap
attribute to the img
element,
you create a server-side image map, which means that the position you clicked on
the image is appended to the URL.
For example, if you clicked 4 pixels from the top and 10 pixels from the left edges of the images, the browser will navigate to the following:
http://java2s.com/page.html?10,4
You can create a client-side image map: clicking on different regions in an image causes the browser to navigate to different URLs.
The key element for a client-side image map is map
with local attributes name
.
If the id
attribute is used,
it must have the same value as the name
attribute.
The map
element can have one or more area
elements.
Each area element marks a region in the image that can be clicked on.
The area
element has local
attributes:alt, href, target, rel, media, hreflang, type, shape, coords
.
The rel, media, and hreflang attributes are new in HTML5. The nohref attribute is now obsolete.
shape
and coords
attributes work together.
The coords
attribute depends on the value of the shape
attribute.
rect
circle
poly
default
The following code shows how to use image map.
<!DOCTYPE HTML>
<html>
<body>
<p>
<img src="http://www.java2s.com/style/download.png" usemap="#mymap"/>
</p><!--from w w w . j av a 2s. co m-->
<map name="mymap">
<area href="a.html" shape="rect" coords="3,5,68,62" alt="test a" />
<area href="b.html" shape="rect" coords="70,5,130,62" alt="test b" />
<area href="c.html" shape="default" alt="test c" />
</map>
</body>
</html>
The usemap
attribute on the img
element associates the map element with the image.