1、第一種:用vertical-align
vertical-align:middle 是依賴div內子元素最高的行高來實現對某元素居中的,而我們只需要建立一個新元素,給他加上inline-block
屬性 再把他高度設置為100%就行了,在下面的<img>設置vertical-align就生效了
<div class="method1"> <span class="tiptop"></span> <img class="test" src="img/Dota2.jpg" alt="dota2"> </div> <style> .method1{ text-align:center; } .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、絕對定位的方式
<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{ width:100px; height:100px; background-color:#0A58A0; } </style>