CSS: semi-transparent border on images

When you display images on a white background (but also on other colors) you’d want to add a border to the image. But adding a ‘normal’ CSS border doesn’t always look very well.

The solution: semi-transparant borders that are not positioned around, but on the images. This subtle design element will make your galleries look way better. (Facebook, Flickr, Google, … they all use it)

no border
No border around/on the images
semi-transparent border on images
Semi-transparent border on images

Adding this borders can be done very easily using CSS.

Technique 1: outline

A first solution is using the outline and outline-offset property in CSS:

img.image {
    outline: 1px solid rgba(0, 0, 0, 0.1);
    outline-offset: -1px;
}

This is very easy and works perfectly in a lot of browsers, but sadly it isn’t supported in Internet Explorer 9 & 10, which have together a market share of over 15% (on the desktop).

Technique 2: psuedo element

Using the :after pseudo element has much better browser support. All modern browsers support it.

div.image-container:after {
    border: 1px solid rgba(0, 0, 0, 0.1);
    content: '';

    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

The  above CSS code will use a pseudo element to position the border right on top the image.

Even though working with the pseudo element is better supported, it can be a bit harder to get it working. People often tend to forget how CSS really works. So mind that the parent div should have position: relative and that :after doesn’t work on img elements. (Look it up, because explaining all this would lead us way too far from the original topic.)