<div class="haveTips" tips='hello world'>Lorem ipsum dolor</div>
div.haveTips {
background-color: #F7F5F1;
color: #BBA985;
font-family: sans-serif;
padding: 1em;
border-radius: 10px;
position: relative;
cursor: pointer;
}
div.haveTips::after {
content: attr(tips);
padding: 5px;
background-color: #B4A078;
box-shadow: 0 0 5px #B4A078;
color: white;
min-width: 5em;
max-width: 100%;
text-align: center;
border-radius: 5px;
position: absolute;
bottom: 100%;
left: 50%;
transform: translate(-50%, -10px);
opacity: 0;
transition: all 0.5s;
}
div.haveTips:hover::after {
opacity: 1;
}
div.haveTips::before {
content: '';
width: 0;
height: 0;
border: 6px solid transparent;
border-top-color: #B4A078;
position: absolute;
top: -10px;
left: calc(50% - 6px);
opacity: 0;
transition: all 0.5s;
}
div.haveTips:hover::before {
opacity: 1;
}
和对话气泡类似,提示框也由矩形和小三角组成。
- 使用选择器
::after
创建的伪元素作为提示框
- 使用选择器
:hover::after
设置样式,使其悬浮时显示 - 结合
absolute position
和transform translate
将提示框放到期望的位置:水平方向中心对其,垂直方向隔开一定空隙。bottom: 100%
,使其放在父组件的上边界之外,下边缘位于父组件的上边缘left: 50%
,使其左边缘位于父组件的中心线translate(-50%, -10px)
,左移自身宽度的50%,上移10px,与父组件保持一点距离content: attr(tips)
,获取html标签的tips属性作为内容,方便在html标签内指定提示框内容
- 使用选择器
::before
创建的伪元素作为小三角形箭头
- 利用
border
属性创建三角形,参考构建三角形的方法 - 使用上述类似的移动方法,将其移到期望位置
- 使用上述一样的方法,使其悬浮时显示
在左右移动时,同时用了 left
和 translate
这2个属性,它们的功能类似,为什么不只用 left
呢?
因为它们的百分比计算基数不同:
left
的基数是父组件的宽度translate
的基数是自身的宽度
两个结合起来,可以使提示框与父组件中心对齐。