07/06/2011

CSS Image Link Hover Problem/Solution

by Cyle
Categories: css
Tags: , ,
Comments: Leave a Comment

I came across a problem today while blogging. My problem was that when I made an image a linked image, only a section of the bottom of the image would change when hovered. Hovering over a regular text link worked fine. Below is an example of my problem along with the CSS and HTML.

The Problem

On my old site with a different CSS there would be a little strip of a border at the bottom whenever I hovered over it. It is the “background-color” property which should be none.

<!-- My CSS -->
<style type="text/css">
  a:hover{
  color: #fff;
  background-color: #2d83d5;
  text-decoration: none;}
 
  a img:hover{
  color: none;
  background-color: none;
  text-decoration: none;}
</style>
 
<!-- And my link -->
<a href="http://www.cconoly.com/blog/images/linux-logo.gif"><img src="http://www.cconoly.com/blog/images/linux-logo.gif"></a>

I would have thought that the a img:hover{} would have done the trick but it didn’t. I found that even without text inside the link tags, it still acted like there was text and only applied a background to that text and not the entire image. Finally I found a solution…

The Solution

The solution was to add a separate class for the linked images. This separate class would make the link not have a background hover effect. I even went an extra step and added a border hover effect to the linked image. The fixed example is below with its CSS and HTML.

<!-- My Old CSS -->
<style type="text/css">
  a:hover{
  color: #fff;
  background-color: #2d83d5;
  text-decoration: none;}
 
  a img:hover{
  color: none;
  background-color: none;
  text-decoration: none;}
 
<!-- The New CSS -->
  a.imghover:hover {
  background: none;
  border: none;}
 
  a.imghover img:hover {
  border: 1px solid #2d83d5;}
</style>
 
<!-- And my link with a separate class added -->
<a class="imghover" href="http://www.cconoly.com/blog/images/linux-logo.gif"><img src="http://www.cconoly.com/blog/images/linux-logo.gif"></a>

I’m sure there is an easier way to do this, but this is the only solution I could think of at the moment. I do not understand why the first CSS example would not remove the background, but it wouldn’t. Hopefully I went through all this trouble so you don’t have to.


Leave a Reply

Your email address will not be published. Required fields are marked *



user-avatar
Today is Tuesday
08/22/2017