Fix Padded Image Links with Negative Margins

Avatar of Chris Coyier
Chris Coyier on

This is a pretty basic trick that will be obvious to many of you. But for whatever reason, the solution to it always kind of eluded me so I’m sharing it here. I like padded links. Where you give links in body content a little padding, background, and rounded corners.

a {
  padding: 2px 6px;
  background: #eee;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;

A “padded” link

The problem is that when you make images into links, this padding shows up in ungainly ways.

Wrong Ways to Fix

How I used to fix it was to use a sledgehammer instead of a chisel. That is, I wrote some jQuery to remove the padding for those images.

$("a:has('img')").css(padding, 0);

I did that because jquery has the .has() function which is able to see if an elements contains another element, which CSS lacks. It might be cool if we could do this in CSS…

a:contains img { padding: 0; }

… but we can’t. Another way would be to add a class to all links that contain images like class="imageLink". I have no particular problem with the semantics of that, but it’s not as future-friendly as I might like. Perhaps a future design of the site doesn’t use padded links and now all those old links have an unneeded class name.

The Easy Way

As it turns out, the easy way to handle this is apply some negative horizontal margins to the image inside.

a img { margin: 0 -6px; }

That will yank the extra padding away from the outside and leave you with a clean nubby-free image.

View Demo

Note that in the demo I used a class to fix the problem, the very thing I told you not to do above. This was just for demo purposes since I wanted a problem image and a fixed image on the same page.