带滚动侧边栏中absolute定位tooltip显示问题求助
侧边栏滚动时Tooltip显示在外层的解决方案
当侧边栏设置overflow-y: scroll后,绝对定位的Tooltip会被容器裁剪,核心原因是滚动容器的overflow属性会限制所有属于该容器包含块的子元素显示范围。要解决这个问题,只需将滚动功能和Tooltip的定位上下文拆分,具体实现如下:
1. 调整DOM结构
给侧边栏添加外层容器,将滚动内容独立到内层容器中,Tooltip保留在原位置:
<div class="sidebar-container"> <section class="sidebar-scroll"> <ul> <li> <a href="#"> <span class="wrapper"> <i></i> <span>Section 1</span> </span> </a> <span class="tooltip">Section 1</span> </li> <li> <a href="#"> <span class="wrapper"> <i></i> <span>Section 2</span> </span> </a> <span class="tooltip">Section 2</span> </li> <!-- 可添加更多li --> </ul> </section> </div>
2. 修改CSS样式
- 外层容器作为Tooltip的定位上下文,不设置
overflow - 内层容器负责滚动功能,设置
overflow-y: auto和固定高度 - 调整Tooltip的定位逻辑,确保显示在侧边栏外侧:
* { padding: 0; margin: 0; } .sidebar-container { position: fixed; top: 40px; left: 0; z-index: 1; } .sidebar-scroll { background: white; box-shadow: 0 .2rem .2rem 0 rgb(150 150 150); font-family: Roboto, Arial, sans-serif; overflow-y: auto; height: 150px; } ul { width: fit-content; padding: .4rem 0 .4rem .4rem; list-style: none; display: flex; flex-flow: column nowrap; gap: .4rem; } li { position: relative; a { display: inline-block; width: 100%; padding-block: .4rem; background: white; overflow: hidden; text-decoration: none; } .wrapper { position: relative; display: flex; flex-flow: row nowrap; align-items: center; justify-content: flex-start; padding: .4rem; background: rgb(240 240 240); border-radius: 50vh 0 0 50vh; color: rgb(50 50 50); text-decoration: none; white-space: nowrap; &:before, &:after { content: ""; position: absolute; top: -20px; right: 0px; width: 20px; height: 20px; background: rgba(0, 0, 0, 0); border-radius: 50%; box-shadow: 10px 10px 0 rgb(240 240 240); z-index: 2900; } &:after { top: initial; bottom: -20px; box-shadow: 10px -10px 0 rgb(240 240 240); } i { display: block; width: 20px; aspect-ratio: 1/1; background: rgb(160 160 160); border-radius: 50%; } span { max-width: 0; overflow: hidden; transition: margin .1s linear, max-width .1s linear; } } .tooltip { position: absolute; top: 50%; left: calc(100% + 1rem); /* 侧边栏外侧,加间距 */ transform: translateY(-50%); scale: 0; opacity: 0; display: block; padding: .6rem 1.2rem; background: rgb(80 80 80); border-radius: .4rem; font-size: .8rem; color: white; white-space: nowrap; transition: transform .2s linear, opacity .1s linear, scale .1s linear; z-index: 999; pointer-events: none; /* 避免Tooltip干扰链接交互 */ } &:hover { .wrapper { background: hsl(210 100% 42%); color: white; &:before { box-shadow: 10px 10px 0 hsl(210 100% 42%); } &:after { box-shadow: 10px -10px 0 hsl(210 100% 42%); } i { background: hsl(0 50% 95%); } } .tooltip { transform: translateY(-50%); scale: 1; opacity: 1; } } }
关键原理
- 拆分滚动容器和定位上下文:外层容器
sidebar-container作为Tooltip的定位基准,不设置overflow,因此不会裁剪Tooltip;内层sidebar-scroll仅负责内容滚动。 - 给Tooltip添加
pointer-events: none,确保鼠标hover时不会触发Tooltip的事件,不影响链接的交互。
内容的提问来源于stack exchange,提问作者Hécalim
相关产品推荐
相关产品推荐

