DEV Community

Cover image for Image Maps with SVG — Back to the Future
Paweł Kowalski for platformOS

Posted on • Updated on

Image Maps with SVG — Back to the Future

If you've been in the field of front-end development long enough, you might remember layouts made out of tables, hover states made using inline JavaScript, visitor counters, and the AltaVista search engine. CSS was much more primitive during that time, SVG probably wasn't supported by any browser, and most people called JavaScript DHTML (Dynamic HTML).

There is a tag in HTML called map. It was heavily used when web pages were often not cut to HTML and CSS, but just one image marked to link to other pages. It allows you to mark parts of the image and attach href (and onclick if that is what you need) to them, so when the user clicks on a particular area, it will behave just like a standard link.

Read about map on MDN.

Problem

Recently, we refactored the platformOS.com website. The Values page had an image with absolutely positioned labels linking to the appropriate content:

Values map

This was done with CSS position: absolute and media queries to set positions on different screens. I could leave it as is, but because the refactor included a rewrite of CSS to TailwindCSS (for both maintenance and performance reasons), I decided to do some research.

Solution

First, I tried to do the image map mentioned earlier, but it didn't work inside SVG. Then I discovered that you could do links in SVG. Every element in SVG has to have its x and y coordinates, so a link has features similar to HTML image map.

A link inside SVG looks very similar to an HTML link:

<a href="https://www.platformos.com">
    <text x="10" y="25">platformOS - Limitless development platform</text>
</a>
Enter fullscreen mode Exit fullscreen mode

This gives you the possibility, for example, to embed a link into your logo SVG so you don't have to use links every time you paste it. I decided to use it to have our values inside one image and not have to deal with media queries to position labels on every breakpoint.

Example:

<svg class="w-full" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1355.94 410.97">
  <g id="Performance">
    <a xlink:href="#performance">
      <rect x="598.2" width="167.65" height="26" fill="#d50037"></rect>
      <g>
        <!-- Letters -->
      </g>
    </a>
  </g>
</svg>
Enter fullscreen mode Exit fullscreen mode

Inspect this page for the full version of the SVG (it is inlined): https://www.platformos.com/values

I hope you will remember the map tag and the fact that SVG has a links when such a once in a decade opportunity presents itself to use any of them. :)

Read more

If you are interested in more performance oriented content, follow me and I promise to deliver original, or at least effective methods of improving your website.

Latest comments (0)