放大图像得到拉伸,用于响应布局



我试图在包装器中包含一个图像,并保持其纵横比。然而,图像会延伸。下面是一个示例amp-html,我正面临这个问题。

<style>
    .image-wrapper {
        width: 150px;
        height: 150px;
        background: teal;
    }
    .image-wrapper img {
        height: auto;
        width: auto;
        max-width: 150px;
        max-height: 150px;
    }
</style>
<div class="image-wrapper">
    <amp-img
        src="http://fyogi.com/public/images/products/mobiles/lg-google-nexus-5x-mqqci.c1.w150.jpg"
        layout="responsive" 
        width="150" 
        height="150">
    </amp-img>
</div>

呈现页面后,这是放大器版本的

<div class="image-wrapper">
    <amp-img src="http://fyogi.com/public/images/products/mobiles/lg-google-nexus-5x-mqqci.c1.w150.jpg" layout="responsive" width="130" height="130" class="-amp-element -amp-layout-responsive -amp-layout-size-defined -amp-layout" id="AMP_1"><i-amp-sizer style="display: block; padding-top: 100%;"></i-amp-sizer>
    <img amp-img-id="AMP_1" class="-amp-fill-content -amp-replaced-content" width="130" height="130" src="http://fyogi.com/public/images/products/mobiles/lg-google-nexus-5x-mqqci.c1.w150.jpg"></amp-img>
</div>

在渲染后由amp添加的样式下方,导致拉伸图像,将最小宽度:100%添加到img元素

.-amp-fill-content {
    display: block;
    min-width: 100%;
    max-width: 100%;
    height: 100%;
    margin: auto;
}

现在,我可以通过添加最小宽度:auto解决问题,但这将违背使用amp-html布局响应的目的,文档明确表示,对于布局响应

元素的大小调整为其容器元素的宽度,并自动将其高度调整为宽度和高度属性给定的纵横比。

问题陈述

我有未知尺寸的图像源,但小于150X150px,理想情况下,宽度或高度都是150px。我需要这个图像在固定的150X150分区的中心/中间(水平和垂直)对齐,如果可能的话,我也希望保持em/rem中的所有尺寸。

尝试在CSS代码中添加amp img

.image-wrapper img, .image-wrapper amp-img {
    height: auto;
    width: auto;
    max-width: 150px;
    max-height: 150px;
}

这可能会有帮助。。。。

object fit:contain增加或减少图像的大小以填充容器,同时保持图像的纵横比。

https://ampbyexample.com/advanced/how_to_support_images_with_unknown_dimensions/

 <style>
.fixed-container {
  position: relative;
  width: 200px;
  height: 200px;
 }
 amp-img.contain img {
  object-fit: contain;
 }
   </style>
<div class="flex">
 <div class="fixed-container m1">
<amp-img class="contain"
  layout="fill"
  src="https://unsplash.it/400/300"></amp-img>
</div>
<div class="fixed-container m1">
<amp-img class="contain"
  layout="fill"
  src="https://unsplash.it/300/300"></amp-img>
 </div>
 <div class="fixed-container m1">
<amp-img class="contain"
  layout="fill"
  src="https://unsplash.it/200/300"></amp-img>
</div>
</div>

以下是可能有所帮助的代码。

.image-wrapper img {
//      object-fit: contain; just this line alone can do below job but it's not working in IE. 
        top: 50%;
        left: 50%;
        width: auto;
        height: auto;
        right: inherit;
        bottom: initial;
        max-height: 100%;
        min-width: initial;
        transform: translate(-50%, -50%);
      }

此代码也适用于响应式AMP转盘。

注意:不要尝试添加!important,否则将进行AMP验证失败。

最新更新