如何调整父容器中的图片尺寸?

时间:2019-11-29 09:32:14

标签: javascript html css reactjs

上传后,我试图调整图像尺寸。假设我上传的图片最初的尺寸为450x700,其父容器的尺寸为400x400。就我而言,我使用object-fit通过保留长宽比来为其父容器设置图像,它看起来像

enter image description here

但是我需要完整显示图像,object-fit在这种情况下不是正确的选择。删除object-fit并用width添加height100%使其完全可见,同时降低质量。这里看起来像

enter image description here

enter image description here

最后一张图片中的原始图片是这个

enter image description here

已更新

实际上,我可以使用object-fit: contain来解决它,但这对我来说不是100%正确的,或者也许没有其他方法。有了contain,我得到了

enter image description here

您会注意到图像的白色背景与容器的背景色(浅灰色)不太吻合。有解决的可能吗?

5 个答案:

答案 0 :(得分:2)

当您说object-fit不起作用时,是因为它正在裁剪图像吗?您是否尝试过将object-fit: cover更改为object-fit: contain

另一种选择是将图像作为背景图像,并将background size设置为contain。这将按比例缩放图像以适合其范围。例如

.image__wrapper {
    background: url(../your-img.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
}

不幸的是,拉伸图像以使其适合总是会变形,因此会降低图像质量。

答案 1 :(得分:1)

您可以使用css属性。

background: url('images_here')no-repeat center center
 background-size: cover (or) contain
 width:400px;
 height: 400px;

答案 2 :(得分:1)

如果希望显示完整图像,则应使用object-fit: contain,请参阅https://www.w3schools.com/css/css3_object-fit.asp

<html>
<head>
<style>
.contain {object-fit: contain;}
</style>
</head>
<body>

<h1>The object-fit Property</h1>

<h2>object-fit: contain:</h2>
<img class="contain" src="SOMEFILENAME.jpg" alt="Paris" style="width:200px"> <!--Put the restricting size value here-->

</body>
</html>

答案 3 :(得分:1)

  

image-parent假设这是您的父容器类。因此,您可以像这样添加css

.image-parent img{
    height:400px;
    width:auto;
    display:block;
    margin:0 auto;
}

答案 4 :(得分:1)

如果它的图像标签可以设置object-fit:contain以及高度和宽度,如果它的背景图像可以设置background-size:contain