Next.js + Tailwind CSS 实现带凹圆角镂空的自定义分段分隔线
数据小陈
结论
单独一个 radial-gradient 只能挖出一个圆形缺口,圆与 section 底边相交的位置仍然是尖角,无法自动形成平滑的内凹圆角。想要这种 concave corner,可以把中央半圆孔和左右两个小圆角孔一起写进 mask,再用 mask-composite: intersect 合并;如果需要更精细地控制形状,也可以直接用 SVG path 做 mask 或 clip-path。
为什么现有写法不够
mask-image里只描述了一个圆心和半径,所以透明区域只是一个圆,圆与底边交界处没有额外过渡。mask要加在顶部紫色 section 本身,加在最外层父容器会把圆形按钮和底部白色区域一并裁掉。- 圆心必须和圆形按钮的圆心对齐。缺口中心落在 section 底边时,
radial-gradient的圆心应放在50% 100%附近,不宜随意偏移。 - 半径要比按钮半径略大,通常多 2 到 4px,避免按钮边缘贴住遮罩边缘。
实现步骤
- 测量圆形按钮半径,确定缺口半径
notchRadius,再为缺口两侧设一个较小的内凹圆角半径cornerRadius。 - 用三个
radial-gradient组成 mask:中央半圆孔、左侧小圆孔、右侧小圆孔。 - 多个 mask 图层使用
mask-composite: intersect,让透明孔取并集。 - 同时写
-webkit-mask-image和-webkit-mask-composite兼容 Safari。 - 把按钮放到与顶部 section 同一个
relative容器里,让按钮中心对齐 section 底边。
代码示例
import { ChevronDown } from 'lucide-react';
export function PostQueueBoard() {
const notchRadius = 30; // 中央缺口半径
const cornerRadius = 10; // 内凹圆角半径
const topHeight = 84; // 与 h-[84px] 保持一致
const notchMask = [
`radial-gradient(circle at 50% 100%, transparent ${notchRadius - 0.5}px, #000 ${notchRadius}px)`,
`radial-gradient(circle at calc(50% - ${notchRadius}px) 100%, transparent ${cornerRadius - 0.5}px, #000 ${cornerRadius}px)`,
`radial-gradient(circle at calc(50% + ${notchRadius}px) 100%, transparent ${cornerRadius - 0.5}px, #000 ${cornerRadius}px)`,
].join(', ');
return (
<div className='relative flex flex-col rounded-xl bg-gray-900 border border-gray-800 p-6 w-full max-w-md'>
<div className='relative'>
<div
className='flex flex-row w-full rounded-xl h-[84px] p-4 items-center justify-between'
style={{
background: 'linear-gradient(90deg, #D6B7F1, #7B2FBE)',
WebkitMaskImage: notchMask,
maskImage: notchMask,
WebkitMaskComposite: 'source-in',
maskComposite: 'intersect',
}}
>
<div className='flex flex-col text-white'>
<span className='font-bold'>Total In Queue</span>
<span className='text-sm'>1 currently processing</span>
</div>
<span className='text-white text-4xl font-bold'>24</span>
</div>
<div
className='absolute left-1/2 -translate-x-1/2 -translate-y-1/2 z-10'
style={{ top: topHeight }}
>
<div
className='h-[28px] w-[28px] rounded-full flex items-center justify-center shadow-lg'
style={{ background: 'linear-gradient(90deg, #B183D9, #9E64D1)' }}
>
<ChevronDown className='text-white' size={16} />
</div>
</div>
</div>
<div className='mt-2 flex flex-col bg-white p-4 rounded-xl min-h-[120px]'>
{/* Section Content */}
</div>
</div>
);
}
注意事项
mask-composite在不同浏览器和旧版 Safari 中的支持并不完全一致。上线前要在目标浏览器里验证;如果仍然出现硬切边,可以改用 SVG path mask。- 在
transparent和#000之间留 0.5px 过渡是为了减少锯齿,具体数值可以按视觉效果微调。 - 如果顶部 section 还要保留
rounded-xl的底部圆角,需要确认 mask 没有把圆角切掉;必要的话把圆角放到外层容器。 - 圆心位置、缺口半径和按钮定位三者要联动。按钮中心不在缺口圆心时,视觉上会显得按钮偏了。
- 布局宽度变化很大时,建议用 CSS 变量或 SVG 方案控制尺寸,避免在多个地方重复写死像素值。
备注:内容仅供参考。
