Using linear gradients to create custom dotted border spacing

A CSS dotted border doesn’t allow for any customisation of the spacing between each dot. In some cases, we can substitute the border for a linear gradient that emulates a dotted border — allowing for customisation of the spacing length.

A dotted border (top) and custom dotted lines using linear gradients.

The Sass mixin below can be used to quickly create a dotted linear gradient with custom spacing between each dot. The alignment argument will add the border to the top or bottom of the element.

$dottedLineSpacing: 6;
@mixin dotted-line($color: #000, $alignment: bottom) {
background-image: linear-gradient(to right, $color 0%, $color (100% / $dottedLineSpacing), transparent (100% / $dottedLineSpacing));
background-position: 0 $alignment; background-size: ($dottedLineSpacing + px) 1px;
background-repeat: repeat-x;
}

The mixin can be modified to allow alignment on the left or right side of an element.

@mixin dotted-line-vertical($color: #000, $alignment: left) {
background-image: linear-gradient(to top, $color 0%, $color (100% / $dottedLineSpacing), transparent (100% / $dottedLineSpacing));
background-position: $alignment 0; background-size: 1px ($dottedLineSpacing + px);
background-repeat: repeat-y;
}

There are downfalls of this using method:

  • It cannot be used on an element with a background image, as the dotted line is itself a background image.
  • Only creates a single border at a time (top, right, bottom, or left).
  • Linear gradients do not respond to a border radius. Only straight borders can be created.
  • Requires browser support for linear gradients.