Eliminating Background Color on Image Links

Usually when defining CSS styles in my projects at last I declare the styles for content depending on the surrounding content-container.

While a standard content block would look like

<div class="content-block">
   <p>
      This is <strong>some strong</strong>
      text and it my also hold a <a href="#">link</a>
   </p>
</div>

Using the class of the surrounding content container (i.e. .content-block in this case) it is rather trivial to define all the necessary styles for basic content formatting for use in e.g. a content management system or blogging software like WordPress. I would then go on an declare my styles:

div.content-block {
   /* some styles for the content-block:
   width, font-color, display, etc. */
}

div.content-block p {
   /* some styles for the
   basic paragraph */
}

div.content-block p a {
   /* some styles for the basic link
   inside the basic paragraph */
}

 While this is convenient in most cases, as you only need one class to identify all styles, I came across some difficulties when using links around images. If you define the link to change it’s background color on hover this will work well on text link, but putting an image inside a link will result in the link’s background color blinking through at the bottom of the image:

The screenshots contain a text link and an image link both derived from the same div.content-block p a link definition. Hovering over the image link (second image) will result in an ugly border at the bottom of the image showing the links background.

Now it would be nice to have an ancestor selector to define a special style on all a elements containing an img element. Something like a < img (in contrast to the child selector a > img). Then you just define all a elements with a contained img element to not show any background color. But we all know … there’s no such thing like an ancestor selector. So what to do, if you don’t want to enhance all links containing images with a special class?

The solution to this is rather simple. Just add a display:block to the image contained by the link:

div.content-block p a img {
   display: block;
}

This will make the surrounding link exactly match the size of the image and hence hides the background of the link:

It’s not really a hack, but in any case at least helpful to know. 

Socialize this