你如何拉伸图像以填充 <div>同时保持图像的纵横比? [英] How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

查看:34
本文介绍了你如何拉伸图像以填充 <div>同时保持图像的纵横比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将此图像拉伸到可能的最大尺寸,而不会溢出它的 <div> 或扭曲图像.

我无法预测图像的纵横比,因此无法知道是否使用:

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

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

我不能同时使用两者(即 style="width: 100%; height: 100%;"),因为这会拉伸图像以适应

.

有一个按屏幕百分比设置的大小,这也是不可预测的.

解决方案

2019 年更新.

您现在可以使用接受以下值的 object-fit css 属性:fill |包含 |封面|无 |缩小

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

举个例子,你可以有一个保存图像的容器:

<img src=""class="container_img";/>

.容器 {高度:50px;宽度:50%;}.container_img {高度:100%;宽度:100%;适合对象:覆盖;}

I need to make this image stretch to the maximum size possible without overflowing it's <div> or skewing the image.

I can't predict the aspect-ratio of the image, so there's no way to know whether to use:

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

or

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

I can't use both (i.e. style="width: 100%; height: 100%;") because that will stretch the image to fit the <div>.

The <div> has a size set by percentage of the screen, which is also unpredictable.

解决方案

Update 2019.

You can now use the object-fit css property that accepts the following values: fill | contain | cover | none | scale-down

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

As an example, you could have a container that holds an image:

<div class="container">
    <img src="" class="container_img" />
</div>

.container {
    height: 50px;
    width: 50%;
}

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

这篇关于你如何拉伸图像以填充 &lt;div&gt;同时保持图像的纵横比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆