Article: Image Replacement With CSS

Status
Not open for further replies.

J-Tag

They call him Danger Man!
Jun 25, 2006
391
2
0
Cananada
Article: Image Replacement With CSS
by James Henderson

I'll be posting some articles here, and linking to them from my blog, as I find it easier than maintaining two separate copies.

With accessibility and search engines comes the want of text in our source code, rather than in images which neither can see (though images have the alt tag, its weight in results is still debatable).
But never fear, as good things call in small packages. CSS image replacement is both easy to do, and isn't taxing on bandwidth or resources.

First off, you have to have an element such as a <div> or a <h1> tag which contains a link. Throw an id on it. In this example, I'll use a header tag with the id of 'logo'.

Code:
<html>
<body>
<h1 id="logo"><a href="#">This is a text link<a/></h1>
</body>
</html>
This is what'll show up in the text editor, for search engines, or for people with disabilities. Now to make it pretty for regular users.

The way that this kind of image replacement works, is by placing the link below the height of the container element so it is out of view, using padding and overflow: hidden, and making the whole image a link by using display: block; The image is used as the container's background.

Note that you'll have to define the width and height of your image on the container element for this to work.

Code:
<html>
<head>
<style type="text/css">
#logo
    {
    width: 80px; /* the width of your image */
    height: 80px; /* the height of your image */
    overflow: hidden; /* makes anything outside of the width of the image invisible */
    background: #000 url(avatar.gif); /* shows the image */
    }
#logo a
    {
    padding-top: 81px; /* puts the text below the area it's able to be seen in */
    display: block; /* makes the whole image clickable as a link */
    font-size: 1px; /* just in case */
    }
</style>
</head>
<body>
<h1 id="logo"><a href="#">This is a text link<a/></h1>
</body>
</html>
It's just that easy!

If anyone doesn't get what I've done here, either PM me or post your questions in a reply to this thread.
 


Status
Not open for further replies.