如何自动调整大图像的大小,使其适合较小宽度的div容器,同时保持其宽高比?


示例:stackoverflow.com-当图像插入到编辑器面板上,并且图像太大而无法放到页面上时,图像将自动调整大小。


当前回答

所有提供的答案,包括已接受的答案,都只能在假设div包装器大小固定的情况下工作。因此,无论div包装器的大小如何,这都是如何实现的,如果您开发响应页面,这非常有用:

在DIV选择器中编写以下声明:

width: 8.33% /* Or whatever percentage you want your div to take */
max-height: anyValueYouWant /* (In px or %) */

然后将这些声明放入IMG选择器中:

width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */

非常重要:

对于DIV和IMG选择器,maxHeight的值必须相同。

其他回答

<style type="text/css">
    #container{
        text-align: center;
        width: 100%;
        height: 200px; /* Set height */
        margin: 0px;
        padding: 0px;
        background-image: url('../assets/images/img.jpg');
        background-size: content; /* Scaling down large image to a div */
        background-repeat: no-repeat;
        background-position: center;
    }
</style>

<div id="container>
    <!-- Inside container -->
</div>

最简单的方法是使用对象拟合:

<div class="container">
  <img src="path/to/image.jpg">
</div>

.container{
   height: 300px;
}

.container img{
  height: 100%;
  width: 100%;
  object-fit: cover;
}

如果您使用Bootstrap,只需添加img响应类并更改为

.container img{
    object-fit: cover;
}

下面的代码改编自以前的答案,由我使用名为storm.jpg的图像进行测试。

这是显示图像的简单页面的完整HTML代码。这很完美,我用www.resizemybrowser.com测试过。把CSS代码放在HTML代码的顶部,放在你的头部下面。把图片代码放在你想要的地方。

<html>
    <head>
        <style type="text/css">
            #myDiv
            {
                  height: auto;
                  width: auto;
            }
            #myDiv img
            {
                max-width: 100%;
                max-height: 100%;
                margin: auto;
                display: block;
            }
        </style>
    </head>

    <body>
        <div id="myDiv">
            <img src="images/storm.jpg">
        </div>
    </body>
</html>

本文可能会帮助您:

.方形{位置:相对;宽度:300px;高度:300px;溢出:隐藏;}国际货币基金组织{位置:绝对;最大宽度:100%;宽度:100%;高度:自动;顶部:50%;左:50%;转换:转换(-50%,-50%);}img.景观{高度:100%;宽度:自动;}<div class=“square”><img src=“https://unsplash.it/400/500“alt=”图像“/></div><div class=“square”><img src=“https://unsplash.it/500/400“class=”landscape“alt=”图像“/></div>

简单的CSS解决方案:如何将不同尺寸的图像放在集合容器中(2017-05-01)

.方形{位置:相对;宽度:441px;高度:200px;溢出:隐藏;边框:1px实心黑色;}国际货币基金组织{最大宽度:100%;/*宽度:100%*/<----它拉伸图像并适合父对象高度:自动;/*转换:转换(-50%,-50%)*/<-----设置垂直和水平中心}img.景观{高度:100%;宽度:自动;}<div class=“square”><img src=“https://cdn.pixabay.com/photo/2020/08/28/12/32/man-5524488__340.jpg“alt=”图像“/></div>

我使用以下代码修复了此问题:

<div class="container"><img src="image_url" /></div>
.container {
    height: 75px;
    width: 75px;
}

.container img {
    object-fit: cover;
    object-position: top;
    display: block;
    height: 100%;
    width: 100%;
}