CSS 将图像原始大小保持在较小的 div 内
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24249635/
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
Keep image original size inside smaller div
提问by Nicoli
I have an image that is 600x400px, and want it inside a smaller div of size 240x200px, but the image shrinks or gets distorted. I want the original size image centered in the smaller div, which would hide some of the image
我有一个 600x400 像素的图像,并希望它在一个 240x200 像素的较小 div 中,但图像缩小或扭曲。我希望原始大小的图像以较小的 div 为中心,这会隐藏一些图像
I wrote this CSS rule to apply to different image sizes.
我写了这个 CSS 规则来适用于不同的图像尺寸。
.theBox {
float: left;
overflow: hidden;
width: 240px;
height: 200px;
}
.theBox img {
display: block;
height:100% !important;
width:100% !important;
}
回答by service-paradis
If you specify a 100% size for your image. Your image will then take 100% of its container.
如果您为图像指定 100% 大小。然后,您的图像将占用其容器的 100%。
The thing you want is keeping your file at its original size, so do not specify any size for your image.
您想要的是将文件保持其原始大小,因此不要为图像指定任何大小。
overflow:hidden
is the key to show only a part of your image.
overflow:hidden
是只显示图像的一部分的关键。
If you want to always have the center of your image visible, you should take a look at this CSS3 property transform:translate(-50%,-50%)
with a proper positioning.
如果您希望图像的中心始终可见,您应该查看transform:translate(-50%,-50%)
具有正确定位的CSS3 属性。
Take a look at this jsfiddleand tell me if it can help you.
看看这个jsfiddle并告诉我它是否可以帮助你。
回答by MrWhite
To maintain the aspect ratio, only size one dimension, the browser will size the other to maintain the aspect ratio. With the dimensions you have given you'll need to set the height to fit the container (as opposed to the width) so not to have any gaps:
为了保持纵横比,只调整一个维度,浏览器将调整另一个维度以保持纵横比。根据您提供的尺寸,您需要设置高度以适合容器(而不是宽度),以免有任何间隙:
.theBox img {
display: block;
height: 100%;
}
Example: jsfiddle
示例:jsfiddle
回答by rahgozar
If you specify a 100% size for your image. Your image will then take 100% of its container. In order to maintain the actual size, you should write an inline style like this: style="width: auto"
如果您为图像指定 100% 大小。然后,您的图像将占用其容器的 100%。为了保持实际大小,您应该编写这样的内联样式:style="width: auto"