javascript 在 CSS 中保持纵横比的同时将图像大小调整到容器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15528002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:06:33  来源:igfitidea点击:

Size image to container while maintaing aspect ratio in CSS?

javascriptcss

提问by user1031947

I have a bunch of images of different (unknown) dimensions.

我有一堆不同(未知)尺寸的图像。

I want to drop these images into a div and have them automatically conform to the dimensions of the div, while maintaining their aspect ratio.

我想将这些图像放入一个 div 并让它们自动符合 div 的尺寸,同时保持它们的纵横比。

In other words, if the image is wider than high, the width will be 100%, and the height will scale accordingly. If the image is higher than wide, the height will be 100%, and the width will scale accordingly.

换句话说,如果图像宽于高,则宽度将为 100%,高度将相应缩放。如果图像高于宽度,高度将为 100%,宽度将相应缩放。

Is there any way to do this in pure css?

有没有办法在纯 css 中做到这一点?

Thanks

谢谢

回答by iambriansreed

Using the css properties max-widthand max-heighton the image will get you where you need to be.

使用 css 属性max-widthmax-height图像将使您到达需要的位置。

Fiddle

小提琴

http://fiddle.jshell.net/sHAQ9/

http://fiddle.jshell.net/sHAQ9/

HTML

HTML

<div>    
    <img src="http://dummyimage.com/200x300/000000/ffffff.png&text=tall%20image"/>
</div>
<div>    
    <img src="http://dummyimage.com/300x200/000000/ffffff.png&text=wide%20image"/>
</div>

CSS

CSS

div {
    width: 150px;
    height: 150px;    
    overflow: hidden;
    background: #ccc;
    margin: 10px;
    text-align: center;
    line-height: 150px;
}
div img {
    max-width: 100%;
    max-height: 100%;
    vertical-align: middle;
}

回答by PlantTheIdea

I do this with my gallery setup:

我用我的画廊设置来做到这一点:

.ScaledImg {
    max-width:100%:
    max-height:100%;
}

The img scales to fit the dimensions of its parent/container based on this, while maintaining its aspect ratio. I haven't tried this with anything other than imgs, but works well for me. No widthor heightdeclarations are needed.

img 基于此缩放以适应其父/容器的尺寸,同时保持其纵横比。除了 imgs 之外,我还没有尝试过这个,但对我来说效果很好。不需要widthheight声明。

回答by imkost

Try this:

试试这个:

<style>
    .fit_image img {
        max-width: 100%;
        max-height: 100%;
    }
    .fit_image {
        width: 400px;
        height: 200px;
    }
</style>

<div class="fit_image">
     <img src="/path/to/image.jpg">
</div>

回答by UnLoCo

Based on @iambriansreed fiddle,
Use zoom on the image when it's smaller than the container

基于@iambriansreed fiddle,
当图像小于容器时使用缩放

div img {
    zoom: 10;
    max-width: 100%;
    max-height: 100%;
    vertical-align: middle;
}

http://fiddle.jshell.net/vcapr0k8/

http://fiddle.jshell.net/vcapr0k8/