方法一、使用display:table-cell
样式
<style> .wrapperbox{border:1px solid red; width:100px; height:100px; display:table-cell; font-size:0; text-align:center; vertical-align:middle; *position:relative;padding:0; overflow:hidden; } .innerbox{text-align:center; vertical-align:middle; width:100px\9; *width:auto;font-size:0; *position:absolute;*top:50%;*left:50%;} img{ max-height:100px; max-width:100px; *position:relative;*bottom:50%;*right:50%;margin:0 auto;} </style>html
<div class="wrapperbox"> <div class="innerbox"> <img src="demo.png" /> </div> </div>此方法div包括层过多; 兼容性:除IE 10及以下不兼容外,谷歌、360、火狐亲测兼容
方法二、使用绝对定位实现居中
样式
<style type="text/css"> .content { background: #dedede; width:500px; height:500px; position:relative; } .content div{ background: red; width:300px; height:300px; position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); } </style>html
<div class="content"> <div>test</div> </div>兼容性:IE 8以上兼容、谷歌、360、火狐亲测兼容
方法三、使用绝对定位实现全屏居中
样式
<style> body{ margin:0px; width:100%; height:100%; } .box{ position:absolute; top:50%; left:50%; width:500px; height:200px; } .content{ position:relative; top:-50%; left:-50%; width:100%; height:100%; background:red; } </style>html
<div class="box"> <div class="content"> </div> </div>兼容性:全部兼容
方法四、使用display:flex
样式
<style> /*居中div的父级*/ .parent{display:flex;justify-content:center;align-items:center;} </style>兼容性:IE10及IE10以上、谷歌、360、火狐亲测兼容
