html代码:
<div class="main">
<img src="运动跑.png" alt=""/>
<h1 class="bigTitle">this is a img</h1>
<p class="smallTitle">--- How ---</p>
</div>
css代码:
.main {
width: 974px;
margin: 0 auto;
position: relative;
}
.bigTitle {
position: absolute;
left: 50%;
top: 100px;
transform: translateX(-50%);
color: white;
text-shadow: 1px 1px 1px rgba(0, 0, 0, .8), -1px 1px 2px rgba(0, 0, 0, .1);
}
.smallTitle {
position: absolute;
left: 50%;
top: 150px;
transform: translateX(-50%);
color: white;
text-shadow: 1px 1px 1px rgba(0, 0, 0, .8), -1px 1px 2px rgba(0, 0, 0, .1);
}
效果如下:
原理如下:
使用定位,将标题文字居于背景图之上,使用left,top确定位置,基于相对定位的父标签进行数值运算,left,top百分值取决于相对定位父标签的宽度值和高度值计算,但是left使用50%后,文本从50%位置显示,并不是整体居中,使用transform形变中的translate平移,x轴左移50%即设置transform: translateX(-50%),这个百分值的计算基于自身的宽度,通俗讲法就是标题中线对准容器(或者是相对定位父标签)的中线。