Have you ever tried to do this?

  a { background-color: #000; }

<a href="somepage.htm"><img src="picWithAlpha.png" /></a>

I always find that at some point I need to clear the background colour because I use a PNG with transparency and as such the background colour shows when I don't want it to.

At the moment I have to do this:

  a.pngfix { background-color: transparent; }

<a class="pngfix"><img src="picWithAlpha.png" /></a>

This requires a manual addition of the pngfix class to only links with images in.

Ideally there would be a forward-looking CSS selector such as img < a (selecting the a that contains an img), but there isn't and so I'm wondering what everyone else is doing to fix this "problem".

  • Wouldn't it be better to only apply a background color to <a> elements that need it, instead of making it a default? Tony Crockford almost 10 years ago
  • That's definitely an option in some scenarios, but here I want it as the default. Either way I have to create an exception adding a class to fix the ones *with* images or adding a class to fix the ones *without*. At the moment, the ones with images is the lesser Simon Hamp almost 10 years ago

2 answers

danwellman 5600

You could fix it with a little jQuery:

 $("a img").parent().css("backgroundColor", "transparent");

If you're already using jQuery it would be a quick and easy fix

Answered almost 10 years ago by danwellman
  • Yeah that's a great idea and I am doing that in certain cases. The problem arises again though if someone disables Javascript. There really should be a solution within CSS and HTML for this sort of thing... Can you imagine the possibilities if you could select parent elements in CSS based on their child objects? Simon Hamp almost 10 years ago
  • It would be nice. Alas the browser manufacturers reckon it'd be incredibly difficult to implement without destroying performance. Olly Hodgson almost 10 years ago
  • I'm trying to do almost the same thing and find it pretty much has to be javascript. Oh well. Daniel Huckstep over 9 years ago

In jQuery 1.4 (not sure about older than 1.4) you can do:

$('a:has(img)').css("backgroundColor", "transparent");

Which may, or may not be faster.

In the original, I think a > img might be faster.

Answered over 9 years ago by Daniel Huckstep