Fancy Inset CSS Image Borders

Posted under CSS on July 7, 2010.

Overview

In this article we will explore how to add a nice, styled, inset double border to any image. This effect works in all modern browsers and degrades gracefully for Internet Explorer.

The objectives of this tutorial are:

  • Add two separately styled inset borders to an image.
  • Use as little CSS and HTML markup as possible.
  • Use only valid CSS and HTML.
  • Degrade to original style for IE.
  • Work on images of all sizes.

Before

After

The HTML Markup

In a perfect world we would only use a single img tag with a class attribute. This is not a perfect world. Because the img tag does not support the CSS pseudo-element :after, we have to wrap our image in a span.

<span class="fancy">< img src="dingo.jpg" /></span>

The CSS

The first step is to apply a simple reset to our span and img tags.

span,img{padding:0;margin:0;border:0;}

Next, we style the wrapper element.

.fancy{
	position:relative;
	display:inline-block;
	font-size:0;
	line-height:0;
}

.fancy:after{
	position:absolute;
	top:1px;
	left:1px;
	bottom:1px;
	right:1px;
	border:1px solid rgba(255,255,255,0.5);
	outline:1px solid rgba(0,0,0,0.2);
	content:" ";
}

Basically, we are using the :after CSS pseudo-element to create a virtual, styleable, child element inside our wrapper span. We then use a combination of the border and outline properties to create two seperately styled borders.

There are a few things going on in the CSS above that you should pay special attention to.

  • Our pseudo-element is positioned absolutely to our wrapper span.
  • The font-size and line-height properties prevent additional white-space from appearing below the image, which would distort our borders.
  • We apply the content property with some white-space to our pseudo-element. If we would have forgotten to do this, the pseudo-element would not show up.

Additionally, :before and :after may be used to apply multiple backgrounds to an element. Well, that's all for now. I hope you learned something about the usefulness of the :after pseudo-element!

Comment

See what others have to say on this topic, or add your own two cents.