在前端开发制作中,图片垂直居中对齐是很常见的,有些是固定高度,有些没有固定高度,分享几种使用 CSS 实现图片垂直&&水平居中的方法,有些可能并不能兼容所有浏览器,大家可以自行选择:
方法一:
- html {
 - width:100%;
 - height:100%;
 - background:url(logo.png) center center no-repeat;
 - }
 
方法二:
- img {
 - position: absolute;
 - top: 50%;
 - left: 50%;
 - width: 500px; /*图片宽度*/
 - height: 500px; /*图片高度*/
 - margin-top: -250px; /* 高度的一半 */
 - margin-left: -250px; /* 宽度的一半 */
 - }
 
方法三:
- html, body, #wrapper {
 - height:100%;
 - width: 100%;
 - margin: 0;
 - padding: 0;
 - border: 0;
 - }
 - #wrapper td {
 - vertical-align: middle;
 - text-align: center;
 - }
 
- <html>
 - <body>
 - <table id="wrapper">
 - <tr>
 - <td><img src="logo.png" alt="" /></td>
 - </tr>
 - </table>
 - </body>
 - </html>
 
方法四:
Flex 技术实现
- .container{
 - width: 1000px;
 - height: 800px;
 - border: 1px solid #ccc;
 - margin: 0 auto;
 - }
 - div.horizontal {
 - height: 100%;
 - display: flex;
 - // justify-content: center;
 - }
 - div.vertical {
 - display: flex;
 - flex-direction: column;
 - justify-content: center;
 - }
 
- <div class="container">
 - <div class="horizontal div1">
 - <div class="vertical">
 - <img src="logo.png" />
 - </div>
 - </div>
 - </div>
 
