简体   繁体   English

在div中按比例缩放图像

[英]Scale image proportionally within a div

I have an image area in which a random image will be visible. 我有一个图像区域,在其中可以看到随机图像。 How do I make the image fit to its width or height within the image area while maintaining the image proportions? 如何在保持图像比例的同时使图像适合其在图像区域内的宽度或高度?

在此处输入图片说明

This is what I tried, but it distorts the image: 这是我尝试过的方法,但它扭曲了图像:

<div style="float:right;"> <!-- img area -->
    <img style="max-width:100%; max-height:100%;" src="rand/greetings.png"/>
</div>

Just set width or height to 100% but not both, this will keep the proportions of the image and allow it to scale. 只需将widthheight设置为100%,但不能同时设置两者,这将保持图像的比例并进行缩放。

<div style="float:right;"> <!-- img area -->
    <img style="width:100%;" src="rand/greetings.png"/>
</div>

EDIT: 编辑:

To prevent an image spilling out of your area vertically try setting a max-height in pixels on the image and image area: 为了防止图像垂直溢出您的区域,请尝试在图像和图像区域上设置最大高度(以像素为单位):

<div style="float:right; max-height:100px;"> <!-- img area -->
    <img style="width:100%; max-height:90px;" src="rand/greetings.png"/>
</div>

如果要保持简单,可以将此图像设置为background-image并使用background-size:contain;

The following will keep an image horizontally aligned within a div (use the full page link and change the browser size to see the image change size) 以下内容将使图像在div中保持水平对齐(使用整页链接并更改浏览器大小以查看图像更改大小)

 #wrap { border:1px solid #000000; position: relative; width: 50%; height: 400px; overflow:hidden; } #wrap > img { width: 100%; position:absolute; top:50%; transform: translateY(-50%); } 
 <div id="wrap"> <img src="http://lorempixel.com/800/800/city/1/" alt="" /> </div> 

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

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