Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background-color on text links on hover but not image links

Tags:

css

I have a CSS rule like this:

a:hover { background-color: #fff; }

But this results in a bad-looking gap at the bottom on image links, and what's even worse, if I have transparent images, the link's background color can be seen through the image.

I have stumbled upon this problem many times before, but I always solved it using the quick-and-dirty approach of assigning a class to image links:

a.imagelink:hover { background-color: transparent; }

Today I was looking for a more elegant solution to this problem when I stumbled upon this.

Basically what it suggests is using display: block, and this really solves the problem for non-transparent images. However, it results in another problem: now the link is as wide as the paragraph, although the image is not.

Is there a nice way to solve this problem, or do I have to use the dirty approach again?

Thanks,

like image 628
Can Berk Güder Avatar asked Nov 07 '08 23:11

Can Berk Güder


3 Answers

I tried to find some selector that would get only <a> elements that don't have <img> descendants, but couldn't find any... About images with that bottom gap, you could do the following:

a img{vertical-align:text-bottom;}

This should get rid of the background showing up behind the image, but may throw off the layout (by not much, though), so be careful.

For the transparent images, you should use a class.

I really hope that's solved in CSS3, by implementing a parent selector.

like image 148
Gabe Avatar answered Nov 07 '22 13:11

Gabe


I'm confused at what you are terming "image links"... is that an 'img' tag inside of an anchor? Or are you setting the image in CSS?

If you're setting the image in CSS, then there is no problem here (since you're already able to target it)... so I must assume you mean:

<a ...><img src="..." /></a>

To which, I would suggest that you specify a background color on the image... So, assuming the container it's in should be white...

a:hover { background: SomeColor }
a:hover img { background-color: #fff; }
like image 24
Timothy Khouri Avatar answered Nov 07 '22 12:11

Timothy Khouri


I usually do something like this to remove the gap under images:

img {
  display: block;
  float: left;
}

Of course this is not always the ideal solution but it's fine in most situations.

like image 37
Massimiliano Torromeo Avatar answered Nov 07 '22 12:11

Massimiliano Torromeo