Image map in css
In this tutorial, we will see how to add clickable area to a background image to create in css the effect of image mapping without using the html element <map>.
This method is used to render part of an image interactive with the mouse on click and is valid for rectangular area.
First, I created a background image representing a top picture (type header) and a bottom menu with 4 buttons:
To this image, I will ad 5 clickable area, the first being the picture of the frog, the other 4 being the 4 buttons of the bottom menu.
To understand better what we will create, I duplicated the above picture and added a white border to each clickable area, their width and height and their position (top and left):
The html structure
The html structure consists of a simple block element div with an unique id which contains 5 elements <a> (the links), each one having their own id (to give each one their unique style) and a class name to the links of the bottom menu which share the same css style (and avoid to repeat the same css rules).
<a href="#nogo" id="link1"></a>
<a href="#nogo" id="link2" class="menu"></a>
<a href="#nogo" id="link3" class="menu"></a>
<a href="#nogo" id="link4" class="menu"></a>
<a href="#nogo" id="link5" class="menu"></a>
The css rules to create the image mapping
We will start with the css style of the main div (id=”image_map”), we specify:
- the width: the same width as the background image
- the height: the same height as the background image
- the background image using the css property background
- the position relative needed next to position its sub elements in an absolute way
The css style of the links inside ‘image_map’:
- display:block; the elements are converted from inline element to block element so that we can specify the width and height
- position:absolute; all the links are positioned in an absolute way in rapport to the main div.
All the links of the bottom menu share the same css property, for this reason I chosed to use a commune class to avoid to repeat the same css rule: the width of 100px, the height of 50px and their position at 340px form the top border of the main div.
Other then that, each has a unique id (link1, link2, link3…) used to impost their specific style.
For the first link which will cover the area of the picture of the frog: the width of 430px, the height of 320px, the vertical position at 10px from the top border and horizontal of 10px from the left border of the main div.
As we have already specify the css rules for the class ‘menu’ of the 4 bottom links, it will remain to specify for each one of them their horizontal position from the left border of the main div.
The result of the image map