An interesting CSS problem: Inner borders

On a recent CSS-Discussion group discussion somebody raised the question of how to create an inner border on an image when hovered over.

The key point of interest in this problem is the word “inner”. An outer border is simply performed by border: 4px solid #f00;.

After a bit more talking and playing around, here’s the solution i’ve come up with.

The HTML

  1. <a href="#" class="innerborder">
  2. <img src="img.jpg" alt="My image" width="361" height="271" border="0" />
  3. </a>

The HTML is simple enough, an anchor element with a nested image element. Nothing too special there, the magic comes in the CSS.

The CSS magic

  1. a.innerborder, a.innerborder img {
  2. float: left;
  3. overflow:hidden;
  4. }
  5. a.innerborder:hover {
  6. border:4px solid #f00;
  7. }
  8. a.innerborder:hover img {
  9. margin: -4px;
  10. }

Here we style the anchor element’s hover state. We break it out of the normal document flow by floating it left, and we also set the overflow to hidden to (obviously) hide the overflowed contents of the anchor.

The floated nested image will push the dimensions of the anchor to the correct size. Then, the negative margin on the image will correct the anchor’s hover border (note: these values must be exact for the effect to work).

And there you are — an inner border on mouse over.

The demo

Update: I’ve updated the code a bit to now be cross browser/platform compatible.
Example image



About this entry