HTML中图片居中显示,不变形的两种方法

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>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值