padding
百分比值无论是水平方向还是垂直方向均是相对于宽度计算的!
<div class="container">
<div class="img-wrap">
<img src="//cdn.wallleap.cn/img/pic/illustrtion/202207261246820.png" alt="cover">
</div>
</div>
<style>
*, *::before, *::after{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.container {
width: 80vw;
background: #EEE;
height: 400px;
}
.img-wrap {
width: 100%;
height: 0;
background: #77CCCC50;
padding-bottom: calc(10 / 16 * 100%);
overflow: hidden;
}
.img-wrap img {
width: 100%;
}
</style>
<div class="container">
<div class="img-wrap"></div>
</div>
<style>
.img-wrap {
width: 100%;
height: 0;
background: #77cccc50;
padding-bottom: calc(10 / 16 * 100%);
background-image: url(https://cdn.wallleap.cn/img/pic/illustrtion/202207261246820.png);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
</style>
图片使用 img 标签还是背景图片形式取决于是否需要搜索引擎搜录,如果需要搜索引擎搜录,那么就需要使用 img 标签
<div class="container">
<div class="img-wrap">
<img src="https://cdn.wallleap.cn/img/pic/illustrtion/202207261246820.png" alt="cover">
</div>
</div>
<style>
*, *::before, *::after{
margin: 0;
padding: 0;
/* box-sizing: border-box; */
}
body {
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.container {
width: 320px;
background: #ffaabb50;
height: 400px;
}
.img-wrap {
width: 100%;
height: auto;
aspect-ratio: 16/10;
}
.img-wrap img {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>