StealThis .dev
Patterns Medium

Magnetic Button

A button that magnetically attracts toward the cursor when nearby, creating a satisfying interactive pull effect.

Open in Lab
cssjsmousemovetransform
Targets: TS JS HTML React

Code

*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: system-ui, -apple-system, sans-serif;
  background: #0f172a;
  color: #f1f5f9;
  min-height: 100vh;
}

.demo {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 2rem;
}

.hint {
  color: #475569;
  font-size: 0.875rem;
  margin-bottom: 1rem;
}

/* --- Magnetic button --- */
.magnet-btn {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 1rem 2.5rem;
  border-radius: 999px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  border: none;
  outline: none;
  /* Smooth snap-back */
  transition: transform 0.4s cubic-bezier(0.23, 1, 0.32, 1);
  will-change: transform;
}

/* Inner text — moves slightly more for depth */
.magnet-btn__inner {
  display: block;
  transition: transform 0.4s cubic-bezier(0.23, 1, 0.32, 1);
  pointer-events: none;
}

.magnet-btn--primary {
  background: #0ea5e9;
  color: #ffffff;
  box-shadow:
    0 0 0 0 rgba(14, 165, 233, 0),
    0 4px 24px rgba(14, 165, 233, 0.3);
  transition:
    transform 0.4s cubic-bezier(0.23, 1, 0.32, 1),
    box-shadow 0.3s ease;
}

.magnet-btn--primary:hover {
  box-shadow:
    0 0 0 4px rgba(14, 165, 233, 0.15),
    0 8px 32px rgba(14, 165, 233, 0.45);
}

.magnet-btn--ghost {
  background: transparent;
  color: #cbd5e1;
  border: 1.5px solid #334155;
  transition:
    transform 0.4s cubic-bezier(0.23, 1, 0.32, 1),
    border-color 0.2s ease,
    color 0.2s ease;
}

.magnet-btn--ghost:hover {
  border-color: #94a3b8;
  color: #f1f5f9;
}

/* Disable for reduced motion */
@media (prefers-reduced-motion: reduce) {
  .magnet-btn,
  .magnet-btn__inner {
    transition: none;
    transform: none !important;
  }
}

Magnetic Button

A button that physically reacts to the cursor — it magnetically pulls toward the mouse when nearby and snaps back smoothly when the cursor leaves.

How it works

  1. On mousemove, calculate the distance between the cursor and the button center
  2. If within the magnetic radius, interpolate the button position toward the cursor
  3. Apply the offset as a CSS translate transform
  4. On mouseleave, animate back to translate(0, 0) with CSS transition

Tuning the effect

  • STRENGTH: How strong the pull is (0.3 = subtle, 0.6 = strong)
  • RADIUS: Distance in px at which the effect activates
  • Transition duration: Controls snap-back speed

When to use it

  • Primary CTA buttons on hero sections
  • Icon buttons in navigation
  • Any interactive element you want to feel “alive”