有没有办法在AMP中包含图像而不知道它的宽度和高度? 我已尝试布局=响应,但它按照给定的高度和宽度拉伸图像,而不是使其响应。(原始图像的纵横比不保持,而是维持给定的高度和宽度值的纵横比)。 我也尝试过layout = fill,它保持宽高比但是如果给定的高度/宽度大于原始图像的高度/宽度,它会创建填充。 如果有人可以帮助我解决这个问题,因为我不知道图像的尺寸,并希望加载正确的宽高比而不填充。
AMP具有静态布局,这意味着必须事先知道每个元素的高度。这就是无法嵌入未知尺寸图像的原因。有两种解决方法:
1.)定义一个固定高度的容器,让图像填充可用空间,同时保持正确的宽高比(这可能会导致一些填充)。这可以通过将layout=fill
与object-fit: contain
CSS属性相结合来实现。
.fixed-height-container {
position: relative;
width: 100%;
height: 300px;
}
amp-img.contain img {
object-fit: contain;
}
<div class="fixed-height-container">
<amp-img class="contain"
layout="fill"
src="https://unsplash.it/400/300"></amp-img>
</div>
2.)另一种选择是裁剪图像以填充可用空间。
.fixed-height-container {
position: relative;
width: 100%;
height: 300px;
}
amp-img. cover img {
object-fit: cover;
}
<div class="fixed-height-container">
<amp-img class="cover"
layout="fill"
src="https://unsplash.it/400/300"></amp-img>
</div>
你可以在ampbyexample.com上找到不同模式的工作样本。