能否仅用CSS实现Tooltip动态定位以避免超出窗口?
纯CSS实现自适应位置的焦点式Tooltip需求
我有一套由无障碍顾问推荐的、仅通过CSS和标签属性实现的基于焦点的弹窗(Tooltip)代码。这套代码在聚焦元素远离窗口边缘时表现正常,但当聚焦元素靠近窗口右侧或底部时,Tooltip会超出窗口范围。目前只能通过给元素提前添加特定标记(比如.corrected类),让Tooltip切换到元素另一侧(或上方),但我需要通用的CSS代码,无需提前知晓聚焦元素位置就能适配可回流的响应式布局。
注:我清楚可以用JavaScript解决该问题,也看过相关讨论,现在只寻求纯CSS的可行方案。
现有示例代码
HTML代码
<div id="wrapper"> <p> <input type="text" /> Place cursor here and hit "tab" key to move focus </p> <a href="#" title="this is just an example link that does nothing">example link 1</a> <div class="rightside"> <a href="#" title="this is just an example link that does nothing">example link 2</a> <br /> <a class="corrected" href="#" title="this only works if I already know it's on the right edge of the screen">example link 3</a> </div> </div>
CSS代码
#wrapper{ margin: 1em; } .rightside{ text-align: right; } *:not(:hover):focus{ position:relative; border: 1px solid red; } *[title]:not(:hover):focus:after { /* show tooltip on focus but user default for hover */ text-align: left; border: 1px solid #fc0; padding: 3px 6px; color: black; background: #fffea1; content: attr(title) !important; position: absolute; width: auto; min-width: 5em; max-width: 15em; transform: translate(0.5em,-30%); } .corrected[title]:not(:hover):focus:after { transform: translate(-100%,-30%); left: -0.5em; }
内容的提问来源于stack exchange,提问作者Aerik
相关产品推荐
相关产品推荐

