Tuesday, October 11, 2011

Hide the text of a link and show a CSS image

Take this example:
<a class=”abc” href=”http://www.abc.net.au”>ABC</a>
And in the CSS:
a.abc {
display:block;
height: 18px;
width:200px;
background-image: url(abc.gif) no-repeat;
text-indent: -1999px
overflow: hidden;
}
a.abc:hover {
background-position: -300px
}
Now in this example and most other examples out there this works great! Until you start turning things off…
Turn off CSS – it works. The images disappear and the old text link remains, great.
Turn off CSS and images – also fine. The CSS never has a chance to load the images or move the text off to the left of screen.
Turn off images only – uh-oh.
Turning off images but still having the CSS working means that the text is still being hidden off to the left of screen. While this is fine for screen readers, it’s no good at all for people running around with their images turned off leaving them without even a hint that there is supposed to be a link there!
This was a bit of a problem… how do you get the CSS to show the text when images are turned off, but hide the text when the images are turned on?

The Solution

My solution probably breaks a few rules, but it seems to work so far. Insert your old pal spacer.gif in to an img tag. (For the n00bs out there – spacer.gif is just a 1px x 1px transparent gif)
Expanding on the earlier example:
<a class=”abc” href=”http://www.abc.net.au”><img alt=”ABC” src=”spacer.gif”/></a>
And in the CSS, we can get rid of the old styles that were being used to remove the text off to the left of screen:
a.abc {
display:block;
height: 18px;
width:200px;
background-image: url(abc.gif) no-repeat;
text-indent: -1999px
overflow: hidden;
}
a.abc:hover {
background-position: -300px
}
So now if no images are being loaded, the image’s alt tag shows up. But if images are being loaded, the alt tag is hidden because the image is loading fine, there is no ‘normal’ text any more and the CSS background images load in as expected.
The downside to this method is that as far as I know you can’t change the appearance of the alt text, but if the users are used to viewing sites with images turned off they’re probably used to it!

Developer and Project Manager: Ashik Mahmud

Odesk Hire Link: 

No comments: