给定一个 HTML 片段
<div class="swiper-slide">
<div layout="row" layout-align="start stretch" flex style="height: 100%;">
<div layout="row" layout-align="center center" flex="grow">
<img src="/media/{{mediaId}}/h/1440">
</div>
</div>
</div>
它是 CSS 作为
img {
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
}
图像确实保持居中并且不会超出其父容器,但是在调整组件大小时它会水平拉伸(stretch)或收缩。是否可以判断图像元素应保持显示图像的纵横比?
最佳答案
将图像显示为容器 block 的背景,根据您的需要进行拉伸(stretch)。
像这样:
<div class="swiper-slide">
<div layout="row" layout-align="start stretch" flex style="height: 100%;">
<div layout="row" layout-align="center center" flex="grow">
<div
class="img-container"
style="background-image: url(/media/{{mediaId}}/h/1440)"
>
</div>
</div>
</div>
</div>
CSS:
.img-container {
width: 100%;
height: 100%;
background-size: cover;
background-repeat: no-repeat;
}
通过这种方式,您可以确保图像不会只在一个方向上拉伸(stretch),使其看起来不那么好看,而是保持比例不变。
关于html - 使用 CSS 防止调整容器内的图像失真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52722597/