Tag Archives: hover

Adding a Border to an Image on Hover

This next issue I want to cover is fairly simple, but I ran into a situation last week where I needed to find a solution to this problem, and I wasn’t sure of the best answer. I wanted to add a border on the hover state of an image. The problem is that when you add a border it adds to the width. The size of the box according to the box model is made up of width+padding+border+margin. So if you only have the border when hovering, the width of the object changes. When you have images in a grid, the problem is very obvious and actually almost nauseating to look at!

To see the problem, it will be clearest if you go to Demo page to see it in action.

A simple solution is to add a border on your image, div, etc. (wherever it is you want the border) that is the same color of your background. Obviously, this will only work if you have a solid color background. In my demo, I do, so I will add a white border initially, and change it to black on hover. That way the size never changes, but things look different on hover.

img { 
  border: 3px solid white; 
} 
img:hover { 
  border: 3px solid black; 
} 

To solve the problem mentioned above, you can instead use outline property. This will work when you have an image or gradient in your background. It will also work when your initial image has a border, but you want to make it larger on hover. The outline property uses the same syntax as the border shorthand.

/* Solve problem on a non-solid background */
img:hover { 
  outline: 3px solid black; 
} 

/* Solve problem where border size changes on hover */
img { 
  border: 1px solid black; 
} 
img:hover { 
  outline: 2px solid black; 
} 

Explanation

The reason this works is that outlines do not add width to your objects. They are not really in the flow of your document, so things don’t change when you hover over something. Outlines are uniform on each side. You cannot set top, right, bottom, left to be different, as you can with borders.

Notice in the second solution, where the border-size is changing, I made the outline 2px. This is so the final size of border is 3px (1+2).

Browser Support

When I first came upon this solution, I read that it did not work in IE. However, I tested in IE8 and it worked fine. It does not work in IE7. So, if hovering in IE7, the border will remain the same. It depends on the importance of the that visual effect to your design if you want to find another solution to work in IE7 or not. Another solution would be to have a 2nd image for the hover state, but that comes at a price because you are downloading more images. In most cases, I’m fine with leaving IE7 hover-borderless, but it would depend on the site and audience of course.