Html 如何在保持 CSS 中的纵横比的同时调整图像大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12320761/
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
How do I resize an image while keeping the aspect ratio in CSS?
提问by user1447941
I have a large image. I want to display it on its on own a web page, and when doing this without any CSS it fills the whole page and is too big to display at once (scroll bars appear). I want to scale it down so it fits the height of the user's screen (not the width). I've found solutions but these stretch the image to fit the whole of the screen -- I don't want this as it ruins the aspect ratio.
我有一个大图像。我想在自己的网页上显示它,并且在没有任何 CSS 的情况下执行此操作时,它会填满整个页面并且太大而无法一次显示(出现滚动条)。我想缩小它以适应用户屏幕的高度(而不是宽度)。我找到了解决方案,但这些方法会拉伸图像以适应整个屏幕——我不想要这样,因为它会破坏纵横比。
Basically, I want to resize an image while keeping the aspect ratio. How do I do this?
基本上,我想在保持纵横比的同时调整图像大小。我该怎么做呢?
回答by Joseph Silber
Just set the width
to auto
:
只需设置width
为auto
:
img {
width: auto;
max-height: 100%;
}
Here's the fiddle: http://jsfiddle.net/6Y5Zp/
这是小提琴:http: //jsfiddle.net/6Y5Zp/
回答by AKHIL P
here is the sample one
这是示例之一
div{
width: 200px;
height:200px;
border:solid
}
img{
width: 100%;
height: 100%;
object-fit: contain;
}
<div>
<img src="https://upload.wikimedia.org/wikipedia/meta/0/08/Wikipedia-logo-v2_1x.png">
</div>
回答by Hoffmann
You can use a div with background-image and set background-size: contain:
您可以使用带有背景图像的 div 并设置背景大小:包含:
div.image{
background-image: url("your/url/here");
background-size:contain;
background-repeat:no-repeat;
background-position:center;
}
Now you can just set your div size to whatever you want and not only will the image keep its aspect ratio it will also be centralized both vertically and horizontally. Just don't forget to set the sizes on the css since divs don't have the width/height attribute on the tag itself.
现在,您可以将 div 大小设置为任何您想要的大小,不仅图像会保持其纵横比,它还将垂直和水平集中。只是不要忘记在 css 上设置大小,因为 div 在标签本身上没有宽度/高度属性。
The background-size property is ie>=9 only though.
背景大小属性只有 ie>=9 。
回答by jose
I think you need to paste a class inside the image you want to show like this
我认为您需要在要像这样显示的图像中粘贴一个类
< image class="image" >
and this is the class
这是班级
.image
text align: center
max width:pixels you want
max height pixels you want
but make sure that both are the same quantity that way wont get out of the screen in height and width.
但要确保两者的数量相同,这样就不会在高度和宽度上脱离屏幕。
or you can play with the width and the height
或者你可以玩宽度和高度