Marching ants animated selection rectangle in CSS

Marching Ants is a common technique for showing a selection area in an image. The selection border has animated dashes to help distinguish between the selection and the image contents.

Marching ants in Photoshop

Marching ants in Photoshop

This is a CSS technique for a rectangular marching ants that has advantages over other common techniques:

  • The contents of the selected area don’t need to be opaque
  • Doesn’t require divs several divs for each edge of the animation

The CSS property border-image will do the heavy-lifting for us. Border-image is a strange beast because the name makes it sounds like an alternative to border-style (e.g. solid, dashed, dotted), but it’s really a 9-slice technique that even can fill the padding and content area with an image.

We’ll start with a 10px x 10px animated gif that is composed of nine tiles: 1×1 in the corners, 1×8 or 8×1 on the edges, and 8×8 in the center. The center tile is transparent so that we can let the area behind out element show through.



Our CSS will set border-image and specify that the slice is 1px from the edge and that the image should repeat instead of being stretched.

.selectionIndicator {
    border-image: image-url('ants.gif') 8 repeat repeat;
    -moz-border-image: image-url('ants.gif') 1 repeat repeat;
    -webkit-border-image: image-url('ants.gif') 1 repeat repeat;

The result is very close to what you see in Photoshop or other programs. It’s great for creating a cropping UI.

marching ants

Major caveat: border-image isn’t supported in IE <= 10.

in Web | 268 Words