html - 仅 CSS 动态大小工具提示
问题描述
我想我已经很接近了,但我正在努力让工具提示完全按照我的意愿工作。我有一个动态构建的 HTML 表,我想为 TD 的内容提供工具提示。为了提高性能,它必须是纯 css(而不是基于 javascript 或事件)。我希望工具提示在悬停时出现在 TD 的上方和中心,下方有一个箭头。我已经完成了这项工作,但我的问题是工具提示的内容有时可能是几行,这会增加工具提示的高度。发生这种情况时,工具提示仍在 TD 的中心,但不再位于其上方,它已向下移动。无论高度如何,我如何才能拥有始终高于 TD 相同数量的工具提示。请帮忙。
html 示例 td:
<td>
<div class="tooltip">
<span>My Tooltip Text</span>
Text in the TD
</div>
</td>
我的CSS:
.tooltip span
{
display: none;
color: #000;
text-decoration: none;
}
.tooltip:hover span
{
display: block;
position: absolute;
background-color: #292929;
margin: -2.8em -1em;
color: white;
padding: 0.5rem 1rem;
border-radius: 4px;
white-space: pre-line;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
text-align: left;
}
.tooltip:hover span::after
{
top: 100%;
left: 50%;
border: solid transparent;
content: '';
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-top: 8px solid #292929;
border-right: 8px solid transparent;
border-left: 8px solid transparent;
border-width: 10px;
margin-left: -40px;
}
解决方案
例如
@keyframes pulse {
0% {
opacity: .5;
transform: translate(-50%, -100%) scale(.5);
}
50%{
opacity: 1;
transform: translate(-50%, -100%) scale(1.2);
}
100% {
transform: translate(-50%, -100%) scale(1);
}
}
.tooltip span
{
color: #000;
text-decoration: none;
transform: translate(-50%, -100%) scale(.5);
position: absolute;
background-color: #292929;
color: white;
padding: 0.5rem 1rem;
border-radius: 4px;
font-size: 1rem;
font-weight: 400;
text-align: center;
box-shadow: 0 0 4px 2px rgba(0,0,0,.2);
width: max-content;
max-width: 200px;
top:0;
left:50%;
margin-top: -18px;
visibility: hidden;
opacity: 0;
}
.tooltip:hover{
position: relative;
}
.tooltip:hover span
{
opacity: 1;
visibility: visible;
transform: translate(-50%, -100%) scale(1);
animation: pulse 1s;
}
.tooltip:hover span::after
{
top: 100%;
left: 50%;
transform: translateX(-50%);
border: solid transparent;
content: '';
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-top: 8px solid #292929;
border-right: 8px solid transparent;
border-left: 8px solid transparent;
border-width: 10px;
}
<br>
<br>
<br>
<br>
<table border="1">
<tr>
<td>Hello</td>
<td>
<div class="tooltip">
<span>My Tooltip Text</span>
Cool text
</div>
</td>
<td>
<div class="tooltip">
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit</span>
Long text
</div>
</td>
</tr>
</table>
推荐阅读
- python - 使用 ruamel 保留合并键和显式键的相对顺序
- sql - 如何在没有连接的情况下覆盖另一个表中的列中的列?
- c# - Asp.Net Core 2.2 身份页面不适用于视图/共享文件夹中的布局
- web - 配色方案转换
- java - 尝试在 Java 中两次处理异常
- javascript - 赋值运算符是否在 javascript 中进行深层复制
- asp.net-mvc - 我的查询字符串没有达到我的操作方法
- regex - Flex 正则表达式
- ios - 使用 iPhone (QT) 重新连接外围设备时出现问题
- jquery - 谷歌地图方向服务正在路由回原点(创建循环),我该如何防止它?