如何用TailwindCSS为侧边菜单<li>标签添加右侧边框作为激活指示器
实现TailwindCSS侧边菜单激活状态右侧边框指示器
要实现激活状态下<li>右侧显示边框的效果,你可以通过相对定位+绝对定位元素的方式实现,具体方案如下:
核心思路
给激活状态的<li>设置相对定位,再添加一个绝对定位的元素作为右侧指示器,让它贴合侧边栏右边缘,同时不打乱原有布局。
修改后的完整代码
<div class="bg-bgcolor h-screen"> <aside class="w-20 bg-white pt-2 rounded-2xl flex flex-col justify-center h-4/5 overflow-hidden"> <ul class="flex flex-col items-center w-full"> <!-- 激活状态的菜单项 --> <li class="relative w-full flex justify-center py-2"> <div class="text-white bg-black p-2 rounded-2xl"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" class="w-6 h-6"> <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25" /> </svg> </div> <!-- 右侧激活指示器 --> <span class="absolute right-0 top-1/2 transform -translate-y-1/2 h-4/5 w-1 bg-black"></span> </li> <!-- 非激活状态的菜单项示例 --> <li class="w-full flex justify-center py-2"> <div class="text-gray-500 p-2 rounded-2xl hover:bg-gray-100"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" class="w-6 h-6"> <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 10.5l4.72-4.72a.75.75 0 011.28.53v11.38a.75.75 0 01-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 002.25-2.25v-9a2.25 2.25 0 00-2.25-2.25h-9A2.25 2.25 0 002.25 7.5v9a2.25 2.25 0 002.25 2.25z" /> </svg> </div> </li> </ul> </aside> </div>
关键调整说明
- 给
<ul>添加w-full:让列表项能铺满侧边栏宽度,为指示器定位提供基础 - 激活状态
<li>设置relative w-full flex justify-center:确保列表项宽度拉满、内容居中,同时作为指示器的定位容器 - 右侧指示器的样式设置:
right-0:让指示器紧贴侧边栏右边缘top-1/2 transform -translate-y-1/2:实现垂直居中h-4/5 w-1 bg-black:定义指示器的高度、宽度和颜色,可按需调整
- 给
<aside>添加overflow-hidden:防止指示器超出侧边栏的圆角范围,保证视觉统一性
你可以通过给<li>添加/移除包含上述样式的自定义类(比如.active)来切换激活状态。
内容的提问来源于stack exchange,提问作者rameez khan
相关产品推荐
相关产品推荐

