<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#preview{
width: 180px;
height: 180px;
background: #ccc;
display: flex;
align-self: center;
justify-content: center;
align-items: center;
}
#imghead{
width:100%;
}
</style>
</head>
<body>
<div id="preview" width="180" height="180">
<img id="imghead" border=0 src="https://ss1.baidu.com/-4o3dSag_xI4khGko9WTAnF6hhy/image/h%3D220/sign=0db336008b025aafcc3279c9cbefab8d/562c11dfa9ec8a13bf872720fe03918fa1ecc055.jpg" width="100%"/>
</div>
</body>
</html>
1.弹性布局使图片水平垂直居中
.swiper{display: flex;margin: auto;justify-content: center;align-items: center;}
.swiper img{width:500px;height:300px;}
注意flex的兼容性再决定是否使用弹性布局
详细可以看这个网站http://www.cnblogs.com/yangjie-space/p/4856109.html
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
4.利用原生js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#preview{
width: 180px;
height: 180px;
background: #ccc;
}
</style>
</head>
<body>
<div id="preview" width="180" height="180">
<img id="imghead" border=0 src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505645781146&di=39926ba4de5d86635f17f145eab21476&imgtype=0&src=http%3A%2F%2F955.cc%2Fzimeiti%2Fimg%2F3244005.jpg"/>
</div>
<!-- 利用原生js使图片自适应居中-->
<script>
window.onload=function(){
var oImg=document.querySelector("#imghead");
var width=oImg.width;
var height=oImg.height;
var rect=clacImgZoomParam(180,180,width,height);
oImg.width = rect.width;
oImg.height = rect.height;
oImg.style.marginLeft = rect.left+'px';
oImg.style.marginTop = rect.top + 'px';
}
function clacImgZoomParam( maxWidth, maxHeight, width, height ){
var param = {top:0, left:0, width:width, height:height};
if( width>maxWidth || height>maxHeight ){
rateWidth = width / maxWidth;
rateHeight = height / maxHeight;
if( rateWidth > rateHeight ){
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
}else{
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
}
param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
}
</script>
</body>
</html>