Monday 13 August 2007

CSS image map

You know what client-side image map is - you assign a map to an image where you specify links for some regions on that image. Different from putting an anchor on image, user gets to different places depending on where on image (s)he presses.

It appears that the same effect may be achieved with HTML + CSS. I've tried it only with rectangular regions. Why reinvent the wheel? Well, CSS allows much more customization of what you do: compare the same task implemented using image maps and CSS. Actually, the studying of the sources of those two pages is the best, but here are the ideas behind CSS implementation:
  1. Image map is a bunch of links on the image - so you'll need a bunch of links as well, on something as well. I used anchors on div, but I think anchors on paragraph would also do. But anchors are a must, if you want :hover event to be detectable on most browsers and not use JS. Some people use similar technology to represent various lists graphically, by putting <a> into <li>.
  2. Now comes the CSS part. Image for an image map will go as BG image for div. Make div position absolute. For all the links, make their position absolute and display block. If the position of div starts at (0,0), you may use same coordinates as in image map, which is great, since there's is a software to create image maps. Note that in image maps coordinates are left right top bottom, while in CSS it is left right width height.
  3. The core is done, some polishing follows. I wanted selected area to differ, so I added a BG image for a:hover. Since I didn't want to create separate image for every link, I've just created small gif with every second pixel transparent. It creates an effect of pseudo transparent shadow on top of real image. Using png image with alpha channel looked better, but not all browsers support it :(
  4. The contents of the link should be empty, otherwise it will clutter the image. Don't worry, links will be clickable, since their size is set explicitly. However, such a map will be unusable on text-only browsers. I've put a contents of links in span, which I made invisible in CSS. So, in browsers that support CSS, we have clear view, while text-only browsers produce a list of nice links.

No comments: