如何用Tailwind CSS实现侧边栏激活项右上/右下凹圆角?
实现侧边栏激活项右侧凹形曲线的解决方案
为什么border-radius不行?
普通的border-radius只能实现外凸圆角,本质是给元素边缘做圆弧外切,没法直接做出向内凹陷的曲线效果。要做右侧的凹口,得用裁剪路径或者伪元素模拟的方式。
方法一:用clip-path裁剪(推荐,适配性强)
通过自定义裁剪路径直接给激活项剪出右侧的凹形,支持任意背景色,不用依赖父元素背景。
步骤1:(可选)给Tailwind添加自定义工具类
如果需要复用这个样式,在tailwind.config.js里加个自定义工具类(需要先装插件:npm install tailwindcss-clip-path):
module.exports = { theme: { extend: { clipPath: { 'sidebar-active': 'polygon(0 0, calc(100% - 12px) 0, 100% 12px, 100% calc(100% - 12px), calc(100% - 12px) 100%, 0 100%)', }, }, }, plugins: [require('tailwindcss-clip-path')], }
步骤2:修改JSX代码
把激活项的样式替换成自定义裁剪类,同时保留左侧圆角的话,可以结合rounded-l-3xl:
<li className={`flex w-[115%] p-2 cursor-pointer text-gray-300 text-sm items-center gap-x-2 transition duration-300 ${ location.pathname === menu.path ? 'active-item bg-white text-black clip-path-sidebar-active rounded-l-3xl' : 'rounded-3xl hover:bg-white hover:text-black' }`} > <Link to={menu.path} className="flex items-center gap-x-4 w-full"> <span className="icon">{menu.icon}</span> <span className={`${!open && 'hidden'} origin-left duration-200`}> {menu.title} </span> </Link> </li>
如果不想装插件,直接用内联样式更省事:
<li className={`flex w-[115%] p-2 cursor-pointer text-gray-300 text-sm items-center gap-x-2 transition duration-300 ${ location.pathname === menu.path ? 'active-item bg-white text-black rounded-l-3xl' : 'rounded-3xl hover:bg-white hover:text-black' }`} style={location.pathname === menu.path ? { clipPath: 'polygon(0 0, calc(100% - 12px) 0, 100% 12px, 100% calc(100% - 12px), calc(100% - 12px) 100%, 0 100%)' } : {}} > {/* 内容不变 */} </li>
提示:把
12px改成你需要的数值,越大凹口越深。
方法二:伪元素模拟凹形(适合固定背景色的侧边栏)
用两个圆形伪元素“盖住”激活项的右上角和右下角,利用侧边栏的背景色营造凹口效果。
步骤1:添加全局CSS
在你的全局样式文件里加这段代码,注意把#你的侧边栏背景色换成实际颜色:
.active-item { position: relative; border-top-left-radius: 1.5rem; border-bottom-left-radius: 1.5rem; overflow: visible; } .active-item::before, .active-item::after { content: ''; position: absolute; right: 0; width: 12px; height: 12px; background-color: #你的侧边栏背景色; border-radius: 50%; } .active-item::before { top: -12px; } .active-item::after { bottom: -12px; }
步骤2:修改JSX代码
移除激活项的rounded-3xl,保留左侧圆角即可:
<li className={`flex w-[115%] p-2 cursor-pointer text-gray-300 text-sm items-center gap-x-2 transition duration-300 ${ location.pathname === menu.path ? 'active-item bg-white text-black' : 'rounded-3xl hover:bg-white hover:text-black' }`} > {/* 内容不变 */} </li>
注意:这个方法要求伪元素颜色和侧边栏背景完全一致,否则会露馅。
内容的提问来源于stack exchange,提问作者Laxman
相关产品推荐
相关产品推荐

