如何仅用CSS复刻目标曲线形状?现有SVG方案曲线不符
仅用CSS复刻指定形状的实现方案
问题描述
我想要仅使用CSS复刻下图中的形状:

我尝试过SVG方案,效果接近但曲线不符合预期,代码如下:
<svg width="450" height="50"> <defs> <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style="stop-color:#555;stop-opacity:1" /> <stop offset="100%" style="stop-color:#333;stop-opacity:1" /> </linearGradient> <filter id="f1" x="0" y="0"> <feDropShadow dx="0" dy="4" stdDeviation="3"/> </filter> </defs> <path d="M0,0 L450,0 L450,20 L300,20 C270,20 250,50 230,50 L0,50 Z" fill="url(#grad1)" /> <path d="M0,0 L450,0 L450,20 L300,20 C270,20 250,50 230,50 L0,50 Z" fill="transparent" filter="url(#f1)" /> </svg>
现在我想改用纯CSS实现该形状,并且还原完全一致的曲线,目前我的CSS代码卡在曲线部分(用红色标记了曲线位置):
<!DOCTYPE html> <html> <head> <style> #top-rectangle { height: 50px; width: 250px; background-color: #555; } #bottom-rectangle { height: 20px; width: 250px; background-color: #555; margin-left: 250px; margin-top: -50px; } #curve { height: 30px; width: 2px; background-color: red; margin-left: 250px; } #curve2 { height: 2px; width: 30px; background-color: red; margin-left: 250px; margin-top: -30px; } </style> </head> <body> <div id="top-rectangle"></div> <div id="bottom-rectangle"></div> <div id="curve"></div> <div id="curve2"></div> </body> </html>
解决方案
可以通过CSS clip-path直接复刻SVG的路径,结合渐变和阴影实现完全一致的效果,无需拆分多个元素:
实现代码
<!DOCTYPE html> <html> <head> <style> .target-shape { width: 450px; height: 50px; /* 直接复用SVG的路径到clip-path,保证曲线完全一致 */ clip-path: path('M0,0 L450,0 L450,20 L300,20 C270,20 250,50 230,50 L0,50 Z'); /* 还原水平渐变 */ background: linear-gradient(to right, #555, #333); /* 模拟SVG的阴影效果 */ box-shadow: 0 4px 6px -3px rgba(0,0,0,0.3); } </style> </head> <body> <div class="target-shape"></div> </body> </html>
细节说明
- 曲线还原:
clip-path: path()直接使用原SVG的路径代码,确保曲线和目标形状完全一致,现代主流浏览器均支持该属性。 - 渐变匹配:用
linear-gradient(to right, #555, #333)还原原SVG的水平渐变效果。 - 阴影替代:用
box-shadow模拟SVG的feDropShadow,参数调整为和原阴影一致的垂直偏移与模糊度。
如果需兼容旧版浏览器,也可将SVG路径转换为百分比格式的polygon实现:
clip-path: polygon(0 0, 100% 0, 100% 40%, 66.7% 40%, 60% 40%, 51.1% 100%, 0 100%);
内容的提问来源于stack exchange,提问作者kru3
相关产品推荐
相关产品推荐

