共计 1540 个字符,预计需要花费 4 分钟才能阅读完成。
需要形容
页面中有一个图片,页面宽度变小(比方关上控制台,拖动边栏),图片宽高,要随之等比例自适应缩放,如下效果图
效果图
实现计划
- 计划一:应用宽度百分比和 vw
- 计划二:宽度百分比加高度被 padding-top 撑开
- 计划三:搭配伪元素
间接上代码,复制粘贴即可应用
计划一:应用宽度百分比和 vw
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.adapt {
width: 36%;
height: 36vw;
background-color: pink;
}
img {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="adapt">
<img src="http://ashuai.work/static/img/avantar.png">
</div>
</body>
</html>
计划二:宽度百分比加高度被 padding-top 撑开
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.adapt {
width: 36%;
height: 0;
padding-top: 36%;
background: pink;
position: relative;
}
img {
width: 100%;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="adapt">
<img src="http://ashuai.work/static/img/avantar.png">
</div>
</body>
</html>
计划三:搭配伪元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.adapt {
width: 36%;
overflow: hidden;
background: pink;
position: relative;
}
.adapt::after {
content: '';
display: block;
margin-top: 100%;
}
img {
width: 100%;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="adapt">
<img src="http://ashuai.work/static/img/avantar.png">
</div>
</body>
</html>
A good memory is better than a bad pen. Write it down…
正文完