一、使用CSS的padding-bottom
属性
1.1 HTML结构
<div class="image-container">
<img src="your-image.jpg" alt="描述">
</div>
1.2 CSS样式
.image-container {
position: relative;
width: 100%; /* 容器宽度自适应 */
padding-bottom: 56.25%; /* 容器高度为宽度的56.25%,适用于16:9的宽高比 */
}
.image-container img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: auto;
}
1.3 代码解释
.image-container
设置了padding-bottom
属性,值为宽度的百分比。在这个例子中,假设图片的宽高比为16:9,因此高度是宽度的56.25%。
- 图片通过绝对定位放置在容器内,宽度设置为100%,高度设置为auto,这样图片就会根据容器的宽度和
padding-bottom
属性自动调整高度。
二、使用CSS的object-fit
属性
2.1 HTML结构
<div class="image-container">
<img src="your-image.jpg" alt="描述">
</div>
2.2 CSS样式
.image-container {
width: 100%; /* 容器宽度自适应 */
height: 0; /* 容器高度为0,由padding-bottom属性控制 */
padding-bottom: 56.25%; /* 容器高度为宽度的56.25%,适用于16:9的宽高比 */
position: relative;
}
.image-container img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover; /* 保持宽高比,并覆盖整个容器 */
}
2.3 代码解释
.image-container
设置了padding-bottom
属性,确保容器的高度与宽度保持一定的比例。
- 图片通过绝对定位放置在容器内,宽度设置为100%,高度设置为100%,
object-fit: cover;
确保图片覆盖整个容器,同时保持其宽高比。
三、总结