Many of us love to use vivid, clean images to enhance a website design. Unfortunately, it may be necessary to embed links into such an image, which can be a hassle.
In this article, we will present a quick and easy way to add links to your images using a small amount of HTML markup and CSS.
To begin, we must initialize our HTML. For this example, we will use the logo presented by Patrick Lin in his previous article:
It contains the following HTML:
<div id="logo">
<h1><a href="/" title="Home Page"><span>Sample Logo</span></a></h1>
</div>
and CSS:
#logo {
background: url(path_to_banner.jpg);
width: 718px;
height: 66px;
padding-left: 62px;
padding-top: 34px;
}
#logo:hover {
background-position: 0 -100px;
}
#logo h1 a span {
display: none;
}
Notice that Patrick uses a span element to mask the text that would normally appear. This method is vital in order to place a well-positioned link in the image.
To begin, let’s add properties to the link element inside the #logo
div:
#logo h1 a {
display: block;
}
This line is key for our link. By displaying the link element as a block, we are able to give it a width and height. Note that by doing so, it is possible to place this link in an area that covers the sample text in our logo.
Next we need to add some dimensions:
#logo h1 a {
display: block;
width: 172px;
height: 44px;
}
Using this width and height, we are able to make the link reside in the correct area for our logo image.
Now that the basics have been presented, let’s move on to one main exception: Internet Explorer.
If you place two or more of these block links on the same image, IE7 and below seem to remove the link attribute. This has been the case with our RSS link in the logo image.
To solve this problem, we have noticed a peculiar case. If we place a background color or image for the link, it seems to work fine. For example:
#logo h1 a {
display:block;
width:172px;
height:44px;
background: #fff;
}
With two block links or more, the above code solves the problem. Unfortunately, having a white background completely hides the actual RSS image. The trick is to use opacity. By setting the opacity to 0, we are able to remove the background color but still maintain the link:
#logo h1 a {
display: block;
width: 172px;
height: 44px;
background: #fff;
filter: alpha(opacity = 0);
}
The opacity for IE is defined in an odd fashion that causes the CSS not to validate.
By placing the last line of code in an ie-only css file, you can still maintain valid CSS in your template.