Tooltip文本定位异常、箭头过宽及inline-block渲染问题咨询
解决Tooltip定位、箭头宽度及inline-block空格问题
1. 修复Tooltip定位到目标元素正上方
初始代码中.tooltip未设置position: relative,导致绝对定位的.tooltiptext会以最近的定位父元素(外层<p>)为基准,而非目标元素本身。即使添加了position: relative和display: inline-block,定位参数也需要调整:
- 给
.tooltip保留position: relative,确保.tooltiptext以它为定位基准 - 修改
.tooltiptext的left和margin-left,让tooltip居中显示在目标元素上方:
.tooltip .tooltiptext { /* 其他属性保留 */ left: 50%; margin-left: -50%; /* 基于自身宽度的一半,实现居中 */ bottom: 120%; /* 调整距离,避免紧贴目标元素 */ }
对于.L和.R类的tooltip,单独调整定位参数以适配侧边元素:
.L .tooltiptext { left: 0; margin-left: 0; text-align: left; } .R .tooltiptext { left: auto; right: 0; text-align: left; }
2. 缩小Tooltip箭头宽度
箭头由CSS边框实现,调整border-width即可缩小宽度,同时对应修改margin-left保持箭头居中:
.tooltip .tooltiptext::after { /* 其他属性保留 */ border-width: 3px; /* 从5px改为3px,缩小箭头 */ margin-left: -3px; /* 对应箭头宽度的一半,保持居中 */ }
侧边tooltip的箭头位置也同步调整:
.L .tooltiptext::after { left: 15%; margin-left: -3px; } .R .tooltiptext::after { left: auto; right: 15%; margin-left: 0; }
3. 消除inline-block导致的多余空格
inline-block元素之间的换行/空格会被渲染为空白,解决方法是给tooltip的父元素设置font-size: 0,再在tooltip内部恢复字体大小:
p.drop.verse { font-size: 0; /* 消除子元素inline-block的空格 */ } .tooltip, p.drop.verse br, p.drop.verse a:not(.tooltip) { font-size: 2em; /* 恢复原字体大小 */ }
修改后的完整Tooltip相关CSS代码
/* Tooltip container */ .tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; font-size: 2em; /* 恢复字体大小 */ } /* Tooltip text */ .tooltip .tooltiptext { visibility: hidden; width: 120px; background-color: #555; color: #fff; text-align: center; padding: 5px 0; border-radius: 6px; /* Position the tooltip text */ position: absolute; z-index: 1; bottom: 120%; left: 50%; margin-left: -50%; min-width: 20em; max-width: 70em; /* Fade in tooltip */ opacity: 0; transition: opacity 0.3s; } .L .tooltiptext { left: 0; margin-left: 0; text-align: left; } .R .tooltiptext { left: auto; right: 0; text-align: left; } /* Tooltip arrow */ .tooltip .tooltiptext::after { content: ""; position: absolute; top: 100%; left: 50%; margin-left: -3px; border-width: 3px; border-style: solid; border-color: #555 transparent transparent transparent; } .L .tooltiptext::after { left: 15%; margin-left: -3px; } .R .tooltiptext::after { left: auto; right: 15%; margin-left: 0; } /* Show the tooltip text when you mouse over the tooltip container */ .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; } /* 消除inline-block空格 */ p.drop.verse { font-size: 0; } p.drop.verse br, p.drop.verse a:not(.tooltip) { font-size: 2em; }
内容的提问来源于stack exchange,提问作者shmuel
相关产品推荐
相关产品推荐

