问题描述
我有一个600x400px的图像,并希望在尺寸为240x200px的较小div内,但是图像会缩小或变形.我想将原始尺寸的图片放在较小的div中,这样会隐藏一些图片
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
我编写了此CSS规则,以适用于不同的图像尺寸.
I wrote this CSS rule to apply to different image sizes.
.theBox {
float: left;
overflow: hidden;
width: 240px;
height: 200px;
}
.theBox img {
display: block;
height:100% !important;
width:100% !important;
}
推荐答案
如果您为图片指定100%的尺寸.然后,您的图片将占用其容器的100%.
If you specify a 100% size for your image.Your image will then take 100% of its container.
您想要的是将文件保持其原始大小,因此请勿为图像指定任何大小.
The thing you want is keeping your file at its original size, so do not specify any size for your image.
overflow:hidden
是仅显示部分图像的键.
overflow:hidden
is the key to show only a part of your image.
如果您想始终使图像的中心可见,则应以适当的位置查看此CSS3属性 transform:translate(-50%,-50%)
.
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.
看看这个 jsfiddle 并告诉我它是否可以帮助您.
Take a look at this jsfiddle and tell me if it can help you.
使用2020年最新的浏览器,查看CSS object-fit
属性.特别是 object-fit:cover;
.看看更新后的 jsfiddle .
With 2020 modern browser, it may be useful to take a look at the CSS object-fit
property. In particular object-fit: cover;
. Take a look at this updated jsfiddle.
这篇关于将图片原始尺寸保持在较小的div内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!