如何在保持图像成比例的同时用图像填充 div?

我发现这个线程ーー 如何拉伸图像填充一个 < div > ,同时保持图像的长宽比?ーー并不完全是我想要的东西。

我有一个 div与一定的大小和图像内。我想 一直都是填写与图像的 div 无论图像是风景或人像。图像是否被截断(div 本身就隐藏了溢出)并不重要。

因此,如果图像是肖像,我希望 width100%height:auto,所以它保持比例。如果图像是风景,我希望的 height100%width to be 汽车’。听起来很复杂,对吧?

<div class="container">
<img src="some-image.jpg" alt="Could be portrait or landscape"/>
</div>

由于我不知道如何做,我只是简单地创建了一个快速的图像,我的意思是什么。我甚至无法准确描述。

enter image description here

我想我不是第一个问这个问题的人。然而,我真的找不到一个解决这个问题的办法。也许有一些新的 CSS3的方式做到这一点-我在考虑弹性箱。知道吗?也许比我想象的还要简单?

342032 次浏览

考虑结合使用 background-size: cover(IE9 +)和 background-image

如果我正确地理解你想要什么,你可以保留宽度和高度的图像属性,以维持高宽比和使用 flexbox为您做居中。

.fill {
display: flex;
justify-content: center;
align-items: center;
overflow: hidden
}
.fill img {
flex-shrink: 0;
min-width: 100%;
min-height: 100%
}
<div class="fill">
<img src="https://picsum.photos/id/237/320/240" alt="" />
</div>

JSFiddle here .

我在 IE9,Chrome31和 Opera 18中成功地测试了这个。但是没有其他的浏览器被测试。一如既往,您必须考虑您的特殊支持需求。

这是我的例子。我使用了一个技巧,将图像设置为 div 容器的背景,背景大小: cover 和背景位置: center center

我把图像的宽度: 100% 和不透明度: 0使它不可见。请注意,我之所以显示我的图像,仅仅是因为我对调用子单击事件有特殊的兴趣。

请注意,虽然我使用的角度是完全无关紧要的。

<div class="foto-item" ng-style="{'background-image':'url('+foto.path+')'}">
<img class="materialboxed" ng-class="foto.picid" ng-src="\{\{foto.path}}" style="opacity: 0;filter: alpha(opacity=0);" width="100%" onclick="$('.materialboxed')/>
</div>
<style>
.foto-item {
height: 75% !important;
width: 100%;
position: absolute;
top: 0;
left: 0;
overflow:hidden;
background-size: cover;
background-position: center center;
}
</style>

结果就是您在所有情况下都定义为最优的结果

一个老问题,但值得更新,因为现在有一个办法。

正确的基于 CSS 的答案是使用 object-fit: cover,它的工作原理与 background-size: cover类似。定位将由 object-position属性负责,该属性默认为居中。

但是在任何 IE/Edge 浏览器或 Android < 4.4.4中都没有对它的支持。而且,Safari、 iOS 或 OSX 都不支持 object-position。填充物确实存在,物体匹配图像似乎提供了最好的支持。

有关该属性如何工作的详细信息,请参阅 关于 object-fit的 CSS 技巧文章以获得解释和演示。

这个应该可以:

img {
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
}

试试这个:

img {
position: relative;
left: 50%;
min-width: 100%;
min-height: 100%;
transform: translateX(-50%);
}

希望这个能帮上忙!

这有点晚,但我只是有同样的问题,最后解决了它与 object-fit: cover与另一个堆栈溢出后(https://stackoverflow.com/a/29103071)的帮助。

img {
object-fit: cover;
width: 50px;
height: 100px;
}

希望这还能帮到别人。

也与 max-heightmax-widthmin-widthmin-height css 属性一起工作。使用像 100%100vh100vw这样的长度单位来填充容器或整个浏览器窗口是非常方便的。

您可以使用 div 来实现这一点。

.img{
width:100px;
height:100px;
background-image:url('http://www.mandalas.com/mandala/htdocs/images/Lrg_image_Pages/Flowers/Large_Orange_Lotus_8.jpg');
background-repeat:no-repeat;
background-position:center center;
border:1px solid red;
background-size:cover;
}
.img1{
width:100px;
height:100px;
background-image:url('https://images.freeimages.com/images/large-previews/9a4/large-pumpkin-1387927.jpg');
background-repeat:no-repeat;
background-position:center center;
border:1px solid red;
background-size:cover;
}
<div class="img">
</div>
<div class="img1">
</div>

CSS object-fit: coverobject-position: left center属性值现在解决了这个问题。

我达到所描述的“最佳情况”的唯一方法,就是把图片作为背景:

.container {
width: 150px;
height: 100px;
background-image: url("http://i.stack.imgur.com/2OrtT.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: 50% 50%;
}
<div class="container"></div>


下面的所有答案都有固定的 widthheight,这使得解决方案“没有响应”。

为了达到效果,但保持图像响应,我使用了以下方法:

  1. 在容器内部放置一个透明的具有所需比例的 gif 图像
  2. 提供一个图像标签内联 CSS 背景与图像你想调整大小和裁剪
.container img{
width: 100%;
height: auto;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
<div class="container">
<img style="background-image: url("https://i.imgur.com/XOmNCwY.jpg");" src="img/blank.gif">
</div>

您可以使用 css flex 属性来实现这一点。请参阅下面的代码:

.img-container {
border: 2px solid red;
justify-content: center;
display: flex;
flex-direction: row;
overflow: hidden;
  

}
.img-container .img-to-fit {
flex: 1;
height: 100%;
}
<div class="img-container">
<img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />
</div>

.image-wrapper{
width: 100px;
height: 100px;
border: 1px solid #ddd;
}
.image-wrapper img {
object-fit: contain;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
}
<div class="image-wrapper">
<img src="">
</div>

只需修正图像的高度并提供宽度 = 自动

img{
height: 95vh;
width: auto;
}

这里有一个答案与支持 IE 使用 object-fit,所以你不会失去比率。使用一个简单的 JS 代码片段来检测是否支持 object-fit,然后将 img替换为 svg:

//ES6 version
if ('objectFit' in document.documentElement.style === false) {
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('img[data-object-fit]').forEach(image => {
(image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
})
})
}


//ES5 version
if ('objectFit' in document.documentElement.style === false) {
document.addEventListener('DOMContentLoaded', function() {
Array.prototype.forEach.call(document.querySelectorAll('img[data-object-fit]').forEach(function(image) {
(image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
}));
});
}
img {
display: inline-flex;
width: 175px;
height: 175px;
margin-right: 10px;
border: 1px solid red
}




/*for browsers which support object fit */


[data-object-fit='cover'] {
object-fit: cover
}


[data-object-fit='contain'] {
object-fit: contain
}
<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
<img src='//picsum.photos/1200/600' />


注意: 还有一些 object-fit填充物可以让 object-fit工作。

下面是一些例子:

我想出的一个简单方法是在容器内的 img 上使用 object-fit: cover

<div class="container">
<img class="image" src="https://mymodernmet.com/wp/wp-content/uploads/2020/11/International-Landscape-Photographer-Year-PhotographER-1st-KelvinYuen-2.jpg">
</div>
.image {
height: 100%;
width: 100%;
object-fit: cover
}


.container {
height: 100px; /*Set any dimensions you like*/
width: 50px;
}

就我所测试的而言,无论要使用的图像的尺寸如何,这都可以工作,并且这满足了您在问题中陈述的“最佳情况”,因为结果是垂直和水平居中的。

我的解决办法是:

<div
style=\{\{
display: "flex",
width: "100%",
height: "100%",
}}
>
<img
style=\{\{
minWidth: "100%",
minHeight: "100%",
objectFit: "cover",
}}
alt=""
src={url}
/>
</div>

上面将放大一个图像,使其成为父容器 掩护
如果你只是需要适应内部,然后改变 objectFitcontain

把所有人都集中起来。即使图像宽度大于容器,也显示整个图像。我只能用 JS 来做这件事。

我知道这不是这篇文章的目的,但这是我来这里的目的,它可能对某些人有用!

<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">


body {
margin: 0;
overflow: hidden;
width: 100vw;
height: 100vh;
background-color: #000;
}


#container{
position: absolute;
top: 0px;
width: 100vw;
height: 100vh;
text-align: center;
}


#my_img{
height: 100%;
width: auto;
}


</style>


</head>
<body>
<div id="container">
<img src="images/filename.jpg" id="my_img">
</div>


<script type="text/javascript">
        

window.onload = function () {
imgElem = document.getElementById('my_img');
if (imgElem.width > document.body.scrollWidth) {
// image is larger than container >> adjust by width and center
imgElem.style.height = 'auto';
imgElem.style.width = '100%';
imgElem.style.position = 'relative';
imgElem.style.transform = 'translateY(-50%)';
imgElem.style.top = '50%';
}
}
        

</script>


</body>
</html>