CSS中有许多方法可以让字体显示在图片上面,下面我们就来介绍两种常见的方法:
方法一:使用position属性
img {
position: relative;
}
img::after {
content: ';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
font-size: 20px;
color: white;
text-align: center;
line-height: 200px;//如果图片高度不确定,可以尝试用line-height使文字垂直居中
} 方法二:使用z-index属性
img {
position: relative;
z-index: 1;
}
span {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
z-index: 2;
font-size: 20px;
color: white;
text-align: center;
} 以上两种方法都可以实现文字显示在图片上方。需要注意的是,如果图片本身是不透明的,使用z-index方法可能会使文字显示不出来。