图片随着屏幕的大小而变化,同事又保证图片不失真.
方法一:
注意加视口
img {
max-width:100%;
height:auto;
}
方法二:使用背景图片 background-size:contain属性;然而这种方法并不是真正的响应式,可以使用媒体查询实现响应式.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Document</title>
<style type="text/css">
div {
width: 100%;
height: 400px;
background-image: url('http://c.hiphotos.baidu.com/image/h%3D300/sign=e3b76ad36081800a71e58f0e813433d6/d50735fae6cd7b89acbea9df032442a7d8330e9f.jpg');
background-repeat: no-repeat;
background-size: contain;
border: 1px solid red;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
方法三:使用H5中的picture标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Document</title>
<style type="text/css">
img {display: block; margin: 0 auto;}
</style>
</head>
<body>
<picture>
<source media="(min-width: 650px)" srcset="http://c.hiphotos.baidu.com/image/h%3D300/sign=e3b76ad36081800a71e58f0e813433d6/d50735fae6cd7b89acbea9df032442a7d8330e9f.jpg">
<source media="(min-width: 465px)" srcset="http://h.hiphotos.baidu.com/image/h%3D300/sign=15d5dd5200d79123ffe092749d355917/48540923dd54564e4d0d6963bfde9c82d1584f04.jpg">
<img src="http://f.hiphotos.baidu.com/image/h%3D300/sign=04083ce4fa03738dc14a0a22831bb073/08f790529822720eb1faa1be77cb0a46f21fabba.jpg" alt="a cute kitten">
</picture>
</body>
</html>