AI CSS Animations

Marching Ants Border

The two-tone dashed outline of a selection box, marching clockwise with resize handles on every corner and edge. The dashes live on an SVG rect with pathLength, so the loop has no seam.

Also known as: animated dashed border css, css border dashed animation, selection box border.

Selection

HTML

<div class="bdr-marching-ants-border">
  <svg class="bdr-marching-ants-border-svg" aria-hidden="true">
    <rect class="bdr-marching-ants-border-base" width="100%" height="100%"/>
    <rect class="bdr-marching-ants-border-ants" width="100%" height="100%" pathLength="100"/>
  </svg>
  Selection
</div>

CSS

.bdr-marching-ants-border {
  --c: var(--bdr-color, #3b82f6);
  font-size: var(--bdr-size, 16px);
  position: relative;
  display: grid;
  place-items: center;
  width: 15em;
  height: 8.5em;
  border-radius: 1em;
  font-family: system-ui, sans-serif;
  font-weight: 600;
  border-radius: 0;
  background: color-mix(in srgb, var(--c) 7%, transparent);
}
.bdr-marching-ants-border-svg {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  overflow: visible;
  pointer-events: none;
}
.bdr-marching-ants-border-svg rect {
  fill: none;
  stroke-width: 0.1em;
}
.bdr-marching-ants-border-base { stroke: color-mix(in srgb, var(--c) 12%, #fff); }
.bdr-marching-ants-border-ants {
  stroke: var(--c);
  stroke-dasharray: 1 1;
  animation: bdr-marching-ants-border-march 0.9s linear infinite;
}
.bdr-marching-ants-border::after {
  content: "";
  position: absolute;
  inset: -0.25em;
  --h: linear-gradient(var(--c) 0 0);
  background:
    var(--h) 0 0, var(--h) 50% 0, var(--h) 100% 0,
    var(--h) 0 50%, var(--h) 100% 50%,
    var(--h) 0 100%, var(--h) 50% 100%, var(--h) 100% 100%;
  background-size: 0.5em 0.5em;
  background-repeat: no-repeat;
  pointer-events: none;
}
@keyframes bdr-marching-ants-border-march {
  to { stroke-dashoffset: -2; }
}

@media (prefers-reduced-motion: reduce) {
  .bdr-marching-ants-border, .bdr-marching-ants-border *, .bdr-marching-ants-border::before, .bdr-marching-ants-border::after, .bdr-marching-ants-border *::before, .bdr-marching-ants-border *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
  }
}

Customizing this snippet

  • Color: set --bdr-color on the element or a parent. Currently previewing #3b82f6.
  • Base size: set --bdr-size. Every other dimension is in em, so the whole thing scales together. Currently previewing 16px.
  • Speed: change the duration on the transition or animation shorthand. Staggered delays are relative, so they keep their rhythm.
  • Reduced motion: the rule at the end of the CSS turns the motion off for people who asked their OS for less of it. Keep it.

Similar border animations