基于中心展开的SVG悬停动画:从GSAP转为纯CSS实现
Replicate Center-Out SVG Hover Animation with Pure CSS
Got it, let's turn that GSAP-powered SVG hover effect into pure CSS—no JS needed! I'll break down exactly how to match the center-expand/shrink behavior you had before.
Core Behavior to Replicate
First, let's recap what your GSAP code did:
- The outer SVG path shrinks from full display to a centered line on hover
- The inner SVG path expands outward from the center (starting fully hidden)
- Animation uses a
power1.inease, and reverses when the mouse leaves
Step-by-Step Implementation
1. SVG Structure (Assumption)
I'll assume your SVG has two paths: an outer border and an inner centered line/cross (like your example). Here's a sample structure:
<svg viewBox="0 0 200 200" class="svg-hover"> <!-- Outer border path --> <path d="M20,20 L180,20 L180,180 L20,180 Z" class="outer-path" /> <!-- Inner centered cross --> <path d="M100,20 L100,180 M20,100 L180,100" class="inner-path" /> </svg>
2. CSS Base Styles
Set up the SVG and path basics first:
.svg-hover { width: 200px; height: 200px; cursor: pointer; } .outer-path, .inner-path { fill: none; stroke: #2d3748; /* Adjust your preferred color here */ stroke-width: 2; /* Match GSAP's power1.in ease with a custom cubic-bezier */ transition: stroke-dashoffset 0.3s cubic-bezier(0.215, 0.61, 0.355, 1); }
3. Outer Path Shrink Animation
We'll use stroke-dasharray and stroke-dashoffset to make the outer border shrink to the center:
.outer-path { /* First, get your path's total length (use DevTools: select path, run `$0.getTotalLength()` in console) */ /* For the sample rectangle above, total length is 640 */ stroke-dasharray: 640; stroke-dashoffset: 0; /* Default: full border visible */ } .svg-hover:hover .outer-path { /* Offset by half the total length to shrink both ends to the center */ stroke-dashoffset: 320; }
4. Inner Path Expand Animation
To make the inner line expand from the center (starting hidden):
.inner-path { /* Total length of the cross is 320 (160 vertical + 160 horizontal) */ stroke-dasharray: 160; /* Half the total length for center-origin expansion */ stroke-dashoffset: 160; /* Default: fully hidden */ } .svg-hover:hover .inner-path { stroke-dashoffset: 0; /* Hover: expand to full length from center */ }
Key Notes
- Path Lengths: Always calculate your actual path lengths (via browser DevTools) instead of using the sample values—this ensures the animation works perfectly for your specific SVG.
- Ease Matching: The
cubic-bezier(0.215, 0.61, 0.355, 1)closely mirrors GSAP'spower1.inease for that smooth, controlled animation feel. - Automatic Reverse: CSS transitions automatically reverse when the hover state is removed—exactly like GSAP's
reverse()method, no extra code needed.
内容的提问来源于stack exchange,提问作者Nine
相关产品推荐
相关产品推荐

