Custom Image Links
Aug 23 2005 11:50 AM
If you've ever tried to spruce up your hyperlinks from the default underline, you've probably noticed that your styles apply not only to your regular links, but to your image links as well.
For example, say you wanted to add a dashed underline to your hyperlinks, then make the underline solid when the user hovers it:
-
a:link, a:visited {
-
border-bottom: 1px dashed #003399;
-
color: #003399;
-
text-decoration: none;
-
}
-
-
a:hover {
-
border-bottom: 1px solid #003366;
-
color: #003366;
-
}
The problem though, is that all of your image links will have that same dashed bottom-border as well which just doesn't look right under an image.
The only way around this predicament is to assign all of the image links to a different class. Simple enough in theory, but it's a pain in the ass to remember to add class="image" every single time you want to use an image link if you ask me.
Use JavaScript
A better way is to let JavaScript do all the dirty work. I've created a function that will go through all the links on a page, see if the link has an img tag in it, and assign the link to class="image" if it does.
Add this in your head section:
-
function customImageLinks() {
-
if (!document.getElementsByTagName) return;
-
var anchors = document.getElementsByTagName('a');
-
for (var i=0; i<anchors .length; i++) {
-
anchor = anchors[i];
-
var images = anchor.getElementsByTagName('img');
-
if (images[0] != null) {
-
anchor.className = "image";
-
}
-
}
-
}
-
-
if (window.addEventListener)
-
window.addEventListener("load", customImageLinks, false)
-
else if (window.attachEvent)
-
window.attachEvent("onload", customImageLinks)
-
else if (document.getElementById)
-
window.onload=customImageLinks
Then you can style the image class however you see fit.
-
a:link.image, a:visited.image, a:hover.image {
-
border-bottom: none;
-
}






Couldn’t you just write a piece of CSS that says:
a:link img {border: 0;}or just set a global rule:
img {border: 0;}I think either of those would work just as well.