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


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


当前回答

<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>

其他回答

一个简单的解决方案是使用Flexbox。将容器的CSS定义为:

.container{
    display: flex;
    justify-content: center;
    align-items: center;
    align-content: center;
    overflow: hidden;
    /* Any custom height */
}

将包含的图像宽度调整为100%,您将在容器中获得一个保持尺寸的居中图像。

目前,对于固定大小的图像(如JPEG或PNG文件),无法以确定性的方式正确执行此操作。

要按比例调整图像大小,必须将高度或宽度设置为“100%”,但不能同时设置两者。如果将两者都设置为“100%”,则图像将被拉伸。

选择高度还是宽度取决于图像和容器尺寸:

如果您的图像和容器都是“肖像形状”或“风景形状”(分别比它们宽或宽),那么高度和宽度中的哪一个都是“%100”并不重要。如果图像是纵向的,而容器是横向的,则必须在图像上设置height=“100%”。如果图像是横向的,而容器是纵向的,则必须在图像上设置width=“100%”。

如果您的图像是SVG,这是一种可变大小的矢量图像格式,则可以自动展开以适应容器。

您只需确保SVG文件中没有在<SVG>标记中设置这些财产:

height
width
viewbox

大多数矢量绘图程序在导出SVG文件时都会设置这些财产,因此每次导出时都必须手动编辑文件,或者编写脚本来进行编辑。

我以这种方式在超链接内水平和垂直居中并按比例缩放图像:

#link {
    border: 1px solid blue;
    display: table-cell;
    height: 100px;
    vertical-align: middle;
    width: 100px;
}
#link img {
    border: 1px solid red;
    display: block;
    margin-left: auto;
    margin-right: auto;
    max-height: 60px;
    max-width: 60px;
}

它在Internet Explorer、Firefox和Safari中进行了测试。

有关居中的更多信息,请参阅此处。

有两种方法可以使图像具有响应性。

当图像是背景图像时。#集装箱{宽度:300px;高度:300px;背景图像:url(https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg);背景尺寸:封面;背景重复:无重复;背景位置:中心;}<div id=“container”><div>在这里运行但是应该使用img标记来放置图像,因为它在SEO方面比背景图像更好,因为您可以在img标记的alt中写入关键字。因此,您可以使图像具有响应性。当图像在img标记中时。#集装箱{最大宽度:400px;溢出:隐藏;}国际货币基金组织{宽度:100%;对象拟合:包含;}<div id=“container”><img src=“https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg“alt=”your_keyword“/><div>在这里运行

<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>