PIMMY asks the CSS Guy if a background image can be used as a hyperlink

PIMMY writes:

Can you hyperlink a background image set inside stylesheet? Or can we set hyperlink location inside style sheet?

No, you cannot hyperlink a CSS background image.

Anything you would want to hyperlink, I would suggest be part of the content rather than the presentation. Perhaps an <img> tag in the mark-up would be a better way to present that particular image.

That said, let’s answer the second question. Yes, you can set a hyperlink location. You can position it in such a way (which is what I assume PIMMY is asking about) so that it appears as if the background image were the hyperlink. Here’s how.

Getting Started

Start with some html. Here’s some:

<p id="sunny">
  I can see clearly now, the rain is gone,<br />
  I can see all obstacles in my way<br />
  Gone are the dark clouds that had me blind<br />
  It's gonna be a bright, bright sunshiny day.
</p>

Give it some style:

p#sunny {
  font:normal 1.2em/1.4em georgia, serif;
  border:4px solid #888;
  background: #fff url(sunny.gif) no-repeat 450px center;
  padding:18px;
  margin:20px 0;
  color:#800000;
}

Now we have a nice starting point – a single paragraph with a background image. View what this looks like.

Insert the Link

Now I’m going to add a link within the paragraph that leads to weather.com.

<p id="sunny">
  I can see clearly now, the rain is gone,<br />
  I can see all obstacles in my way<br />
  Gone are the dark clouds that had me blind<br />
  It's gonna be a bright, bright sunshiny day.
  <a id="linky" href="http://www.weather.com"></a>
</p>

In order for the link to appear like it’s the background image, I need to style it accordingly. First, I’ll add position:relative; to the sunny paragraph.

p#sunny {
  position:relative;
  font:normal 1.2em/1.4em georgia, serif;
  border:4px solid #888;
  background: #fff url(sunny.gif) no-repeat 450px center;
  padding:18px;
  margin:20px 0;
  color:#800000;
}

Next, I’ll style the anchor link that I’ve just inserted with the id of linky. I want it to have the same dimensions as the sunny background image, which is 100px by 100px. Also, I’ll use position:absolute; to place the hyperlink tag directly over the background image.

p#sunny a#linky {
  display:block;
  width:100px;
  height:100px;
  position:absolute;
  top:20px;
  left:450px;
}

Now see the paragraph again, and note that when you hover the mouse over the sun, the mouse indicates a hyperlink that leads to weather.com.

Again, this has “don’t do this” written all over it. Any image you would want to turn into a hyperlink should be in the html, not a CSS background image. Not to mention that if you resize the text, suddenly the alignment is out of whack. But there may be instances where faking it is preferred, so if you ever do this, please do so with the understanding of how easily it can break, and code accordingly.