简体   繁体   English

规模 <img> 适合 <div> 约束-首选无背景图片

[英]Scale <img> to fit <div> constraints - preferred to do without background image

I have a div that is set to 100% the height of my window, and a max-width of 66% of the window's width. 我的div设置为窗口高度的100%,最大宽度设置为窗口宽度的66%。 html and body are set to 100% and overflow:none, so there's no scrolling permitted/possible. html和body设置为100%且溢出:无,因此不允许/不可能滚动。

I want to be able to scale an arbitrary <img> to fill as much as the space as possible. 我希望能够缩放任意<img>来填充尽可能多的空间。 I'd prefer not to use background images, due to existing JS code that interacts with the <img> element. 由于现有的与<img>元素交互的JS代码,我不希望使用背景图像。

This seems like an obvious starting point: 这似乎是一个明显的起点:

<img style="height:100%;max-width:66%">

But the max-width seems to come from a percentage of the browser's HEIGHT, rather than its width. 但是最大宽度似乎来自浏览器高度的百分比,而不是宽度。 And it won't keep its aspect ratio, which is definitely an undesired effect! 而且它不会保持其纵横比,这绝对是不希望的效果!

I could use JS to accomplish this task, but would prefer a CSS solution if there is one? 我可以使用JS完成此任务,但如果有CSS解决方案,则更喜欢使用CSS解决方案? It seems like it should be simple, but I have a feeling it's not... 看起来应该很简单,但是我感觉并非如此...

You can use the css property object-fit. 您可以使用CSS属性object-fit。

<img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />
.cover {
  object-fit: cover;
  width: 50px;
  height: 100px;
}

See example here: http://codepen.io/afonsoduarte/pen/EaOROW 在此处查看示例: http : //codepen.io/afonsoduarte/pen/EaOROW

If the img is within the div , then it's using 66% of the width of the div , which is already 66% of the width of body if I understand correctly. 如果imgdiv ,则它使用的是div宽度的66%,如果我理解正确的话,它已经是body宽度的66%。 You can also make images resize automatically and maintain their aspect ration by setting img {width: auto; max-width: 100%;} 您还可以通过设置img {width: auto; max-width: 100%;}自动调整图像大小并保持其纵横比img {width: auto; max-width: 100%;} img {width: auto; max-width: 100%;} within your CSS, leaving the height unchanged. img {width: auto; max-width: 100%;} ,保持高度不变。

When setting percentage-based widths on an element, the width is typically calculated based on the width of the element's parent, which is why your image may have looked smaller than you expected. 在元素上设置基于百分比的宽度时,通常会根据元素父元素的宽度来计算宽度,这就是为什么图像看起来比预期的要小的原因。

I found an answer that I like over here: 我在这里找到了喜欢的答案:

https://stackoverflow.com/a/26648877/1058739 https://stackoverflow.com/a/26648877/1058739

Quoted in case his answer disappears: 引用以防他的答案消失:


Here's a hackish solution I discovered: 这是我发现的一个骇客解决方案:

#image {
    max-width: 10%;
    max-height: 10%;
    transform: scale(10);
}

This will enlarge the image tenfold, but restrict it to 10% of its final size - thus bounding it to the container. 这会将图像放大十倍,但将其限制为最终大小的10%-因此将其限制在容器上。


Perfect for my needs, I think. 我认为,这非常适合我的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM