HTML Images
29 March 2025 | Category: HTML
Here’s a comprehensive explanation for HTML Images, Image Maps, and Background Images:
HTML Images
What Are HTML Images?
Images are used to enhance the content of a web page by providing visual representation. In HTML, images are embedded using the <img>
tag.
Syntax:
<img src="image-path" alt="description" />
Attributes:
src
: Specifies the path to the image file.alt
: Provides alternate text if the image cannot be displayed.width
andheight
: Set the dimensions of the image (in pixels or percentage).
Example:
<img src="flower.jpg" alt="A beautiful flower" width="300" height="200" />
Adding a Title:
The title
attribute displays a tooltip when you hover over the image.
<img src="flower.jpg" alt="A beautiful flower" title="Hover to see this message" />
Image Maps
What Are Image Maps?
An image map allows you to define clickable areas within an image. Each area can link to different destinations.
Steps to Create an Image Map:
- Use the
<img>
tag with theusemap
attribute. - Define the clickable areas with the
<map>
and<area>
tags.
Example:
<img src="world-map.jpg" alt="World Map" usemap="#worldmap" />
<map name="worldmap">
<!-- Rectangle Area -->
<area shape="rect" coords="34,44,270,350" href="https://example.com/region1" alt="Region 1" />
<!-- Circle Area -->
<area shape="circle" coords="500,300,60" href="https://example.com/region2" alt="Region 2" />
<!-- Polygon Area -->
<area shape="poly" coords="120,300,150,350,100,400" href="https://example.com/region3" alt="Region 3" />
</map>
Attributes of <area>
:
shape
: Defines the shape of the clickable area:rect
: Rectangle.circle
: Circle.poly
: Polygon.
coords
: Specifies the coordinates for the shape.href
: Destination URL for the area.alt
: Description of the area.
Background Images
Adding Background Images
Background images are used to set an image as the backdrop of an element or the entire page. They are defined using CSS.
Basic Syntax:
selector {
background-image: url("image-path");
}
Example:
<style>
body {
background-image: url("background.jpg");
background-repeat: no-repeat; /* Prevents repeating the image */
background-size: cover; /* Ensures the image covers the entire area */
background-position: center; /* Centers the image */
}
</style>
Fixed Background:
To make the background image fixed while scrolling:
body {
background-attachment: fixed;
}
Best Practices
- Optimize Image Size: Use compressed images to reduce load times.
- Responsive Images: Use percentages or media queries for scalable images.
- Accessibility: Always include an
alt
attribute for images. - Fallback for Background Images: Use a background color as a fallback for older browsers or if the image fails to load.