我需要使这张图像拉伸到最大尺寸,而不溢出它的<div>或倾斜图像。

我无法预测图像的纵横比,所以没有办法知道是否使用:

<img src="url" style="width: 100%;">

or

<img src="url" style="height: 100%;">

我不能同时使用(即style="width: 100%;高度:100%;"),因为这将拉伸图像以适应<div>。

<div>的大小由屏幕的百分比设置,这也是不可预测的。


当前回答

这不是一个完美的解决方案,但这个CSS可能会有所帮助。缩放是这段代码的工作原理,理论上,对于小图像,因子应该是无限大的,但在大多数情况下,2、4或8就可以了。

#myImage {
    zoom: 2;  //increase if you have very small images

    display: block;
    margin: auto;

    height: auto;
    max-height: 100%;

    width: auto;
    max-width: 100%;
}

其他回答

我在寻找一个类似的问题时遇到了这个问题。我正在制作一个响应式设计的网页,页面上放置的元素的宽度设置为屏幕宽度的百分比。高度用vw值设置。

因为我用PHP和数据库后端添加了帖子,纯CSS是不可能的。然而,我确实发现jQuery/javascript的解决方案有点麻烦,所以我想出了一个整洁的解决方案(至少我是这么认为的)。

HTML (php)

div.imgfill { float: left; position: relative; background-repeat: no-repeat; background-position: 50% 50%; background-size: cover; width: 33.333%; height: 18vw; border: 1px solid black; /*frame of the image*/ margin: -1px; } <div class="imgfill" style="background-image:url(source/image.jpg);"> This might be some info </div> <div class="imgfill" style="background-image:url(source/image2.jpg);"> This might be some info </div> <div class="imgfill" style="background-image:url(source/image3.jpg);"> This might be some info </div>

通过使用style="",可以让PHP动态更新我的页面,css样式和style=""将最终在一个完美覆盖的图像中结束,缩放以覆盖动态div标签。

这招对我很管用

div img {
    width: 100%;
    min-height: 500px;
    width: 100vw;
    height: 100vh;
    object-fit: cover;
}

有一个更简单的方法,只使用CSS和HTML:

HTML:

<div 
    class="fill" 
    style="background-image: url('path/to/image.jpg');">
</div>

CSS:

.fill {
    background-size: cover;
    background-position: center;
    width: 100%;
    height: 100%;
}

这将把你的图像作为背景,并拉伸它以适应div的大小而不失真。

HTML:

<style>
#foo, #bar{
    width: 50px; /* use any width or height */
    height: 50px;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
}
</style>

<div id="foo" style="background-image: url('path/to/image1.png');">
<div id="bar" style="background-image: url('path/to/image2.png');">

JSFiddle

...如果你想设置或改变图像(以#foo为例):

jQuery:

$("#foo").css("background-image", "url('path/to/image.png')");

JavaScript:

document.getElementById("foo").style.backgroundImage = "url('path/to/image.png')";

试试这个

HTML:

<div class="container"></div>

CSS:

.container{
background-image: url("...");
background-size: 100%;
background-position: center;
}