使图片垂直&水平居中的CSS实现方法

来源:互联网 发布:安卓系统刷windows系统 编辑:程序博客网 时间:2024/05/18 01:31

方法一:使用CSS的 background-image

html {    width:100%;    height:100%;    background:url(logo.png) center center no-repeat;}

方法二:使用CSS的 margin 实现

img {   position: absolute;   top: 50%;   left: 50%;   width: 500px; /*图片宽度*/   height: 500px; /*图片高度*/   margin-top: -250px; /* 高度的一半 */   margin-left: -250px; /* 宽度的一半 */}

方法三:table 方式实现
CSS:

html, body, #wrapper {   height:100%;   width: 100%;   margin: 0;   padding: 0;   border: 0;}#wrapper td {   vertical-align: middle;   text-align: center;}

HTML:

<html><body>   <table id="wrapper">      <tr>         <td><img src="logo.png" alt="" /></td>      </tr>   </table></body></html>

方法四:Flex 技术实现
CSS:

.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;}

HTML:

<div class="container">    <div class="horizontal div1">        <div class="vertical">            <img src="logo.png" />        </div>    </div></div>
0 0