...

View Full Version : Images As Links In CSS



miggsy007
10-17-2004, 05:16 PM
Hi all. I am trying to get an image to act as a link using css, and am having a few problems.

My site has a menu positioned on the left that is 10em wide and then my content is on the right set with a left-margin of 10em to allow for the menu.

Within the content section I have a pic 100px high so it works like so:

CSS:

#content {
background: #000;
margin-left: 10em;
text-align: center;
color: #fff;
padding: 10px;
}

.pic {
margin-left: auto;
margin-right: auto;
height: 100px;
background: url(../graphics/pic.jpg) center no-repeat;
}

XHTML:

<div id="content">
This is the content, with a pic just below.

<p class="pic">
</p>

</div>

This worked just fine. Then I decided to make the pic a link by altering the XHTML like so:

<div id="content">
This is the content, with a pic just below.

<a href="link.html">
<p class="pic">
</p>
</a>

</div>

This kind of works... except the area that acts like a link extends across the whole body of the content, not just the pic that only takes up a small space in the middle of the content div. Changing the background line on .pic in my css to :

background: #fff url(../graphics/pic.jpg) center no-repeat;

showed me that this was because even though I only had a small image the css box it was in reached the sides of the content div.

Also putting the <a> round the <p> invalidates my xhtml even though it still works.

Ignoring the invalid xhtml problem for a bit I added a definate width to my image. By leaving the background of the image white and leaving the background of the content black, it was fairly obvious that the class 'pic' now had space either side of it, it didn't go the sides of the content div any more. . But the link area still extends to the sides of the div.

Can anybody help me sort it so only the pic is a link? And if you can make it so my xhtml validates again my gratitude will know no bounds.

Thanks,

Miggsy007

Antoniohawk
10-17-2004, 06:14 PM
Welcome to Coding Forums. :)

Is there a specific reason that the image has to be the background? Why not just encase an image tag in a link?

miggsy007
10-17-2004, 10:40 PM
Thanks for the response. There isn't any particular reason for it, I should have explained a bit clearer in my original post. I'd rather keep the pics under css control so they don't appear in the unstyled page, but if thats not possible then doing what you suggested will be fine.

It's just if it is possible I'd like to do it like I'm trying to.

Cheers,

Miggsy007

Antoniohawk
10-17-2004, 11:28 PM
Alright, the following should work. :)

.image {
background: transparent url(yella.gif) repeat;
width: 100px;
height: 100px;
display: block;
}
...
<a href="http://www.google.com/" title="Google" class="image"></a>

miggsy007
10-18-2004, 05:58 PM
Thanks mate. That works fine, all is as it should be.

Miggsy007



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum