CSS Animation Example: Magnetic Button

A "Magnetic Button" subtly pulls toward the user's cursor as they hover near it, creating a highly engaging and physical feel.

While true magnetic buttons that perfectly track the cursor require JavaScript, we can create a convincing CSS-only version using an invisible grid overlay. By placing four transparent div areas over the button (representing Top-Left, Top-Right, Bottom-Left, Bottom-Right), we can use the ~ (general sibling combinator) to shift the button towards whichever quadrant is currently being hovered via transform: translate().

Here is the code to create the CSS-Only Magnetic Button animation.

View Output Full Screen Preview

Accessibility Considerations

As this movement is unexpected, it may be disorienting or annoying to some users. It's best practice to use the prefers-reduced-motion media query to detect if a user has configured their system to minimize non-essential motion.

Here we create a static, predictable experience for these users by completely disabling the transform translation.


@media (prefers-reduced-motion: reduce) {
    .magnetic-btn {
        transition: none;
    }
    .m-area:hover ~ .magnetic-btn {
        transform: translate(-50%, -50%); /* Keep centered */
    }
}