1 background
按照最短边最大显示原则,最长的边超出部分隐藏,图片整体水平垂直居中,图片不拉伸
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#imgbox {
margin: calc(50vh - 250px) auto;
width: 500px;
height: 500px;
background-image: url(https://img-blog.csdnimg.cn/20191113174018452.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
</style>
</head>
<body>
<div id="imgbox">
</div>
</body>
</html>
效果 原图
2 img居中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.box {
width: 50%;
margin: 50px auto;
}
.img-box {
width: 300px;
height: 200px;
overflow: hidden;
position: relative;
z-index: 1;
border: 1px solid red;
}
.img-box img {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
margin: auto;
z-index: -1;
*zoom: 1;
}
.img-box:before {
content: "";
display: inline-block;
padding-bottom: 100%;
width: 0.1px;
/*必须要有数值,否则无法把高度撑起来*/
vertical-align: middle;
}
</style>
</head>
<body>
<div class="box">
<span>行内元素垂直居中</span>
<div class="img-box">
<img src="../images/1555658617201.png" />
</div>
</div>
</body>
</html>