HTML & CSS - - By Craig Buckler

How to Duplicate Elements Using CSS3 Box Shadows

Take a look at the following demonstration page in Firefox, Chrome, Safari, Opera, IE9 or IE10:

demonstration

The circles are created using DOM elements rather than canvas, SVG, Flash or another alternative.

Question: without looking at the source code, how many DOM elements are required?

The answer should be obvious if you read the title of this article. Just one element is used; in this case, it’s a single DIV with the ID ‘element’. It’s actually an invisible circle since its color matches the background.

The other circles are defined in CSS using a little-known feature of the box-shadow property. It permits you to duplicate the shape of any element in any location, at any size, in any color any number of times. The property has six arguments:

  1. inset: (optional) if defined, the shadow will appear inside the element
  2. horizontal: the x distance from the element
  3. vertical: the y distance from the element
  4. blur: (optional) the blur radius, i.e. 0 for no blur
  5. spread: (optional) the distance the shadow spreads, i.e. 1px extends the shadow 1 pixel in all directions so it’s 2px wider and taller than the parent element
  6. color: the shadow color

We can use the horizontal and vertical distances for relative positioning. The spread can be positive or negative to make the shadow larger or smaller than the parent element. Since multiple shadows can be defined, we can duplicate the original shape any number of times, e.g.

#element
{
	width: 100px;
	height: 100px;
	background-color: #ccc;
	border-radius: 50px;
	box-shadow: 120px    0px 0  15px #f00,
				-60px  104px 0   0px #0f0,
				-60px -104px 0 -15px #00f;
}

example box-shadow

Remember your shape can have also :before and :after pseudo elements with their own box-shadows.

Next question: is this useful?

That’s more tricky to answer, but it’s an option to consider when developing pages with repeating shapes. It could certainly help reduce page weight.

Obviously, it’s possible to take the technique to extremes and create whole scalable graphics using box-shadows, e.g.

However, this is fairly pointless given that a PNG or SVG is likely to be more efficient and easier to create. But let me know if you use the repeating box-shadow technique for anything interesting…

Sponsors