I have been working on a link rollover effect for my website, to achieve the following:
┌────────────────────────────┐
│ ┌──────────────────┐ │
│ │ <a> │ │
│ └──────────────────┘ │
│ │
│ <img> │
└────────────────────────────┘
I want the background image, <img>
, to appear when the mouse hovers only over the link, <a>
. In other words, when the link part is hovered over, I want the image behind it to appear (or change state) without becoming "clickable" as well. And I would like to do it with only CSS.
I didn't use the common CSS background/sprite approach because A) no matter how I marked it up, if the <img>
was anywhere within the <a>
tag, the whole image became "clickable" as soon as it was revealed, and B) I wanted to use larger, better quality images, and including them in the HTML avoided having to use Javascript or browser hacks to pre-load them.
My solution was to put the <a>
and the <img>
within a parent <li>
(since this is essentially part of the "menu" or site navigation), and then use the adjacent sibling selector (+) to make the <img>
change when the <a>
is hovered over. At it's most basic, the CSS looks like this:
li {
size and position declarations; /*The size is the same as the contained image.*/
}
li a {
absolute size and position declarations for the link area;
z-index: 2; /*I use the z index to make sure the link stays above the image.*/
}
li img {
absolute size and position declarations for the image;
z-index: 1;
display: none;
li a:hover + img {
display: block;
}
And the basic HTML looks like this:
<ul>
<li><a href="page.htm"> </a><img src="image.jpg"></li>
<li>...
</ul>
If you want to see it in action, I've got a test version up at www.joshuakirby.net/test (be gentle—I am self taught, and I readily admit I'm no expert at coding). It works great in all the major browsers I've tried, except IE. I haven't gotten it to work properly in any IE version, even in IE9. The rollover flickers, much like sprites did in IE6, and the link isn't always clickable on the first, or even second try.
Does anyone know why IE is giving me grief with this? Is there some fix to make IE render this CSS like the rest of the browsers? Or, if the whole method I've come up with is crap, can anyone think of a more cross-browser friendly, elegant way to make this rollover work using CSS?
I'm not a newbie at web design, and I can also tackle JS and PHP if I have to. The idea of doing it all with CSS just appealed to me. Thanks in advance for your help!
The flickering is caused because IE doesn't seem to be respecting the z-index values of the link when it has no content. However if you set the background of the links (e.g. #craftsLink a) to a transparent png image it seems to fix the issue & the site works in IE7+.