简体   繁体   English

响应式设计中的图像拉伸

[英]Image Stretching in responsive design

I am having an image in different size.我有不同大小的图像。 All having huge size images.都有巨大的图像。 I need to show the image without any stretch inside a container.我需要在容器内没有任何拉伸地显示图像。 That container had some height.那个容器有一定的高度。 So I have show the image to fit inside the container without any stretch.所以我已经展示了图像以适应容器而没有任何拉伸。 I need to use image in html not as background image.我需要在 html 中使用图像而不是背景图像。 Here is my code这是我的代码

 .image-container { height: 420px; width: 100%; } @media (max-width: 480px) { height: 310px; } @media (max-width: 375px) { height: 275px; } @media (max-width: 320px) { height: 240px; } .image-container img { max-height: 100%; object-fit: contain; max-width: 100%; display: block; margin: 0 auto; }
 <div class="image-container"> <img src="http://media.gettyimages.com/photos/under-the-tree-picture-id480585809" /> </div>

When I use above code image is stretching.当我使用上面的代码时,图像正在拉伸。 Is there any way to fix this?有没有什么办法解决这一问题? Please suggest any solution for this.请为此提出任何解决方案。

Thanks in Advance.提前致谢。

Always reset the margins and paddings of all elements first.始终首先重置所有元素的边距和填充。

 * {
    margin: 0;
   padding: 0;
}

If height or width is auto it will not stretch / mutate the original image.如果高度或宽度是自动的,它不会拉伸/改变原始图像。

.img-container {
    width: 420px;    // your width
}

.img-container img {
    width: 100%;
    height: auto;
    display: block;
}

Remove the media queries.删除媒体查询。 Your syntax is incorrect the correct syntax for using them is :您的语法不正确,使用它们的正确语法是:

@media (max-width: 480px) {
  .img-container {
      // some changes in the class props
   }
   .another-class-change-for-480px-max-width-of-screen {

   }
}

在 css 中使用max-width而不是width以避免拉伸

.img-container img{ max-width:100%; height:auto;}

Latest solution for this is using object-fit for IMG .对此的最新解决方案是使用object-fit for IMG

Note: Not supported in IE11.注意: IE11 不支持。 Check support here .在此处查看支持

Both images are same.两个图像是一样的。 Second image has object-fit: cover第二张图片有object-fit: cover

 .fitImage { width: 200px; height: 200px; object-fit: cover; }
 <img src="https://i.picsum.photos/id/292/200/300.jpg" alt=""> <img src="https://i.picsum.photos/id/292/200/300.jpg" alt="" class="fitImage">

Using jQuery使用 jQuery

 $(document).ready(function() { $(".fitImage").each(function(index) { var imageUrl = $(this).find('img').prop("src"); $(this).css('background-image', "url(" + imageUrl + ")") }); });
 .fitImage { height: 200px; width: 200px; background-size: cover; background-position: center; } .fitImage img { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="fitImage"> <img src="https://i.picsum.photos/id/292/200/300.jpg" alt=""> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM