(1)第一种:用vertical-align
<div class="method1"><span class="tiptop"></span><img class="test" src="img/Dota2.jpg" alt="dota2">
</div><style>
.method1{text-align:center;
}
/*vertical-align:middle 是依赖div内子元素最高的行高来实现对某元素居中的,而我们只需要建立一个新元素,给他加上inline-block属性 再把他高度设置为100%就行了,在下面的<img>设置vertical-align就生效了*/
.tiptop{height:100%;display:inline-block;vertical-align:middle;
}
img{vertical-align:middle;
}
</style>
(2)第二种:flex布局(注意浏览器兼容性)
<div class="method2"><img src="img_p1_title.png">
</div><style>
.method2 {display: flex;justify-content: center; //弹性盒子对象在主轴上的对齐方式align-items: center; //定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。background-color:#00a0e9;height:200px;
}
.method2 img {width:20px;height:30px;background-color:#0A58A0;
}
</style>
(3)position:absolute;绝对定位方式
<div class="method3"><span>第三种方法</span>
</div><style>
.method3 {width:100%;height: 200px;font-size: 18px;position: relative;background-color:#00a2d4;
}
.method3 span {width:100px;height:100px;background-color:#00ACED;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);}
</style>
(4)使用display:table-cell配合vertical-align:center(淘宝也是这样用的)
<div class="method4"><span>第四种方法</span>
</div><style>
.method4 {width: 200px;height: 200px;vertical-align: middle;display: table-cell; /*只支持IE8+及现代浏览器,与position:absolute;或float:left;属性尽量不一起用*/text-align: center;background-color:#00ACED;
}
.method4 span{width:100px;height:100px;background-color:#0A58A0;
}
</style>
简单易懂吧,点个赞