纯css实现tooltip
前言
tooltip
这东西非常符合我的口味和审美。但在我理解中这东西是需要js来计算位置动态生成的。因此在制作博客系统的时候,也懒得造轮子而引入了antd
,但引入这框架会因此引入许多无用的css样式以及会增大webpack打包后的js体积,就算按需加载了组建,打包后整体大小也有800多K,这无疑加重了我这轻博客
的负担。因此,通过万能的google,学到了如何用纯css实现tooptip,这里也来记录一下
原理
1: 通过css伪类生成tooptip提示框
2: 通过强大的css3 attr()
方法,配合自定义的data
属性实现文字传递
3: 增加适当的过渡效果
代码实现
html
<div data-info='小埋'>
<img src="avatar.jpeg" alt="小埋">
</div>
css
*{
margin:0;
box-sizing: border-box;
}
div{
margin-top:200px;
margin-left:200px;
position: relative;
display: inline-block;
cursor: pointer;
}
img{
width:50px;
height: 50px;
border-radius: 50%;
}
div::before{
position: absolute;
left:50%;
bottom: 100%;
content: '';
border: 6px solid transparent;
margin-bottom: -1px;
border-top-color: rgba(17,17,17,.9);
transform: translate(-50%,10px);
opacity: 0;
transition: all .18s ease-out .18s;
}
div:hover:before{
opacity: 1;
transform: translate(-50%,0);
}
div:hover:after{
opacity: 1;
transform: translate(-50%,0);
}
div::after{
opacity: 0;
position: absolute;
left:50%;
bottom: 100%;
margin-bottom: 11px;
background-color: rgba(17,17,17,.9);
padding:5px 10px;
content: attr(data-info);
color:#fff;
font-size: 12px;
text-align: center;
transform: translate(-50%,10px);
white-space: nowrap;
border-radius: 4px;
transition: all .18s ease-out .18s;
}
踩坑
刚开始直接在<img />
标签上使用时,发现:after
和:befor
都不能生效:
As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content.
Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.
因此 <img />
<input />
<br />
这些自闭和标签存在浏览器兼容性问题,平时使用伪元素时要注意!
总结&收获
centent
属性不止能写一个自定义的string,还能:使用attr()
配合data属性,用counter()
计数,用url()
链接一张图片或者链接- 伪类不能用在自闭和标签上