How do you add a link inside an SVG image file?

9.8k Views Asked by At

I'm having trouble trying to place a clickable link within my SVG image. I've read a few articles but I still cannot seem to get the hang of it, I would greatly appreciate if anyone could guide me on what I may be doing wrong & how I can resolve the issue with my code, Thank you. I'll add a snippet below:

        <div class="apps">

            <svg id="app-button" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000">
                <path d="M0 0h24v24H0V0z" fill="none" />
                <path d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0
                        -6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-
                         4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z" />
                
        </div>
2

There are 2 best solutions below

1
On

there's no need to add link to svg just enclose them inside anchor tag

<a href="somelink.com">
<svg></svg>
</a>
0
On

Links can be placed inside an svg element by use of the xlink namespace, see https://www.w3.org/wiki/SVG_Links.

For the example in the question you could use something like this,

<div class="apps">
        <svg id="app-button" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"
            xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
            <a xlink:href="http://localhost">
            <path d="M0 0h24v24H0V0z" fill="none" />
            <path d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0
                        -6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-
                         4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z" />
            </a>
        </svg>
    </div>

By placing a reference to the xlink namespace in the svg element (xmlns:xlink="http://www.w3.org/1999/xlink") we can use an anchor element like <a xlink:href="...">...</a> around whatever part of the svg image we wish to make clickable. In this case only the paths are clickable, not the entire svg viewbox as would be the case if we wrapped the whole <svg>...</svg> in a standard html anchor element.